c++ - 循环的每次迭代都重置计时器

标签 c++ timer

我的目的是创建一个程序来分析不同数量的样本,并且每个样本都有时间限制。所以定时器必须为每个样本重置。同样,必须是一个 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/

相关文章:

c++ - 解构表达式

c++ - Qml 中的 FileDialog 在 Release 中不起作用

java - ScheduledExecutorService 不会像 Timer 那样结束线程

javascript - 如何在一定时间间隔后重复调用函数

iOS 更新重新加载内容计时器

c++ - 如何命名同时充当其他集合容器的 B+Tree 键/值映射集合

c++ - 重载 operator-、operator< 和 operator >

c++ - 数据结构可以称为实例化的抽象数据类型吗?

python - 如何让我的程序休眠 50 毫秒?

java - 使用计时器自动关闭 JOptionPane.showconfirmDialog