2015-09-01 73 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

謝謝!我會嘗試它! –