2015-09-01 70 views
0

我的意图是创建一个程序,分析不同数量的样本,每个样本都有时间限制。所以定时器必须重置每个样本。同样,必须是一个while循环,它确保程序不会运行太久。重置计时器的每次迭代

代码:

#include <cstdlib> 
#include<stdio.h> 
#include <iostream> 
#include <vector> 
#include <algorithm> 
#include <ctime> 
#include <cmath> 
#include <unistd.h> 

//All functions declaration 


int main(){ 
//function which read all the sample to analyse 

for (int sample=0;sample<numOfSamples;sample++){ 

srand(time(NULL)); 

float tMax = tMax();//A function which calculates the maxium time for that sample 

clock_t t; 
t=clock(); 

//Some more functions which are not important 

time= (clock()-t)/CLOCKS_PER_SEC; 

    while(time<tMax){ 

    //Do different functions 

    time=(clock()-t)/CLOCKS_PER_SEC; 
    cout<<"Timer: "<<time<<endl; 

    }//End of while 
}//End of For Loop (Samples) 
}//ENd of main 

这是我的代码,当你看到有我的计时器没有重启但因为我不知道如何使用它。但是这是计时器的主要问题,它总是0.所以它总是低于tMax。

如何重置计时器并获得大于0的值?

+0

Wy你需要重置计时器吗?只需测量时间和使用时间差异即可。顺便说一句你在哪个系统上运行?如果在Linux上,阅读[time(7)](http://man7.org/linux/man-pages/man7/time.7.html) –

+2

C++ 11 has [''](http:// en.cppreference.com/w/cpp/chrono)标准标题 –

回答

1

也许,您的计算机速度足够快,以便测量时间总是远远少于一秒并四舍五入为零。

当进行基准测试时,最好确保您的计算时间超过半秒,或许通过重复计算多次。

如果在Linux上,请阅读time(7)。考虑使用<chrono>与C++ 11(即g++ -std=c++11 -Wall -g -O编译)

你可以的clock()结果转换为双浮点:

clock_t starttime= clock(); 
do_some_long_computation(); 
clock_t endtime= clock(); 
cout << "long computation took: " 
    << ((double)(endtime-starttime)/(double)CLOCKS_PER_SEC) 
    << endl; 
+0

我怀疑这个链接很快就会死去。 http://en.cppreference.com/w/cpp/chrono/duration/duration_cast –

2

由于巴西莱说,你可以使用<chrono>

// create chrono start time 
auto startTime = std::chrono::system_clock::now(); 

//Some more functions which are not important 

// get elapsed time 
auto elapsedTime = std::chrono::system_clock::now(); 
std::chrono::duration<double> elapsed_seconds = elapsedTime - _startTime; 

// check if duration expires 
auto numSeconds = elapsed_seconds.count(); 
while (numSeconds < tMax) 
{ 
    // Do different functions 

    // check again 
    elapsedTime = std::chrono::system_clock::now(); 
    elapsed_seconds = elapsedTime - _startTime; 
    numSeconds = elapsed_seconds.count(); 
} 
+0

谢谢!我会尝试它! –