计时函数在C ++中花费多长时间的最佳方法是什么? [英] What is the best way to time how long functions take in C++?
问题描述
在C#中,我将启动Stopwatch类,以对某些方法花费多长时间进行快速而肮脏的计时.
In C# I would fire up the Stopwatch class to do some quick-and-dirty timing of how long certain methods take.
在C ++中,这等效于什么?有内置的高精度计时器吗?
What is the equivalent of this in C++? Is there a high precision timer built in?
推荐答案
以前,我已经为这种情况实现了一个计时器:实际上,我最终得到了一个具有两个不同实现的类,一个用于Windows,一个用于POSIX.
I've implemented a timer for situations like this before: I actually ended up with a class with two different implemations, one for Windows and one for POSIX.
原因是Windows具有 QueryPerformanceCounter()
函数使您可以访问非常精确的时钟,这是此类计时的理想选择.
The reason was that Windows has the QueryPerformanceCounter()
function which gives you access to a very accurate clock which is ideal for such timings.
但是在POSIX上不可用,因此我只使用了 boost.datetime 的类来存储开始时间和结束时间,然后从中计算持续时间.它提供了高分辨率"计时器,但是分辨率是不确定的,并且因平台而异.
On POSIX however this isn't available so I just used boost.datetime's classes to store the start and end times then calculated the duration from those. It offers a "high resolution" timer but the resolution is undefined and varies from platform to platform.
这篇关于计时函数在C ++中花费多长时间的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!