本文介绍了计算C ++中经过的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要计算我的功能经过的时间。现在我正在使用std :: clock,据我了解,这是在测量CPU时间,可能与实时不同。

I need to calculated time elapsed of my function. Right now i am using std::clock and from what i understand this is measuring CPU time, which could be different from real time.

std::clock_t start;
double duration;

start = std::clock();

someFunctionToMeasure();

duration = (std::clock() - start) / (double)CLOCKS_PER_SEC;

所以我想知道两件事


  1. std :: clock如何工作?

  1. How does std::clock exactly work? is it just measuring CPU when its computing that function?

是否有更好的方法来测量计算我的函数所花费的时间?

Is there a better way to measure time elapsed of computing my function?


推荐答案

使用< chrono> ,您需要的代码如下所示:

Using <chrono>, the code you need could look like this:

using clock = std::chrono::system_clock;
using sec = std::chrono::duration<double>;
// for milliseconds, use using ms = std::chrono::duration<double, std::milli>;

const auto before = clock::now();

someFunctionToMeasure();

const sec duration = clock::now() - before;

std::cout << "It took " << duration.count() << "s" << std::endl;

如果您多次需要此代码段,并且开始/结束大约是您调用 someFunctionToMeasure()的作用域的入口和出口点,将其包装到一个实用程序类中可能会很有意义,该类在构造函数和析构函数中对 now()进行两次调用。

If you need this snippet multiple times and start/end are approximately entry and exit points of the scope in which you invoke someFunctionToMeasure(), it might make sense to wrap it into a utility class that makes the two calls to now() in constructor and destructor.

这篇关于计算C ++中经过的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 15:16