用C++测量经过的时间

Measure time elapsed in C++

本文关键字:时间 经过 测量 C++      更新时间:2023-10-16

可能重复:
linux 上的快速运行时间

如何测量函数在C++中执行所需的时间?如果我能把时间控制在几分之一毫秒,那将是最好的,但如果不能,精确到一毫秒就足够了。如果这意味着什么的话,我正在运行Ubuntu 11.04。

性能测量的最佳时钟是系统范围的实时时钟。在Linux中,可以将clock_gettime函数与CLOCK_MONOTONICCLOCK_MONOTONIC_RAW一起使用。这些将给你纳秒的精度。

#include <ctime>
int main(){
    clock_t start = clock();
    // your program goes here
    clock_t ends = clock();
    cout << "Time elapsed: " << (double) (ends - start) / CLOCKS_PER_SEC << endl;
    return 0;
}