我的目的是创建一个程序来分析不同数量的样本,并且每个样本都有时间限制。所以定时器必须为每个样本重置。同样,必须是一个 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 的值?
最佳答案
正如 Basile 所说,您可以使用 <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();
}
关于c++ - 循环的每次迭代都重置计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32329003/