我想测量循环中函数的速度.但是为什么我这样做的方式总是打印"0"而不是9位十进制精度(即纳秒/微秒)的高分辨率时序?
这样做的正确方法是什么?
#include#include #include int main() { for (int i = 0; i <100; i++) { std::clock_t startTime = std::clock(); // a very fast function in the middle cout << "Time: " << setprecision(9) << (clock() - startTime + 0.00)/CLOCKS_PER_SEC << endl; } return 0; }
如何克服clock()
低分辨率
具有C++和Linux的高分辨率计时器
QueryPerformanceCounter
在OSX上相当于Windows'
Konstantin T.. 6
将时间计算函数for () { .. }
移到语句之外,然后将总执行时间与测试循环中的操作数分开.
#include#include #define NUMBER 10000 // the number of operations // get the difference between start and end time and devide by // the number of operations double diffclock(clock_t clock1, clock_t clock2) { double diffticks = clock1 - clock2; double diffms = (diffticks) / (CLOCKS_PER_SEC / NUMBER); return diffms; } int main() { // start a timer here clock_t begin = clock(); // execute your functions several times (at least 10'000) for (int i = 0; i < NUMBER; i++) { // a very fast function in the middle func() } // stop timer here clock_t end = clock(); // display results here cout << "Execution time: " << diffclock(end, begin) << " ms." << endl; return 0; }
注意:std :: clock()缺乏足够的精度来进行性能分析.参考.
将时间计算函数for () { .. }
移到语句之外,然后将总执行时间与测试循环中的操作数分开.
#include#include #define NUMBER 10000 // the number of operations // get the difference between start and end time and devide by // the number of operations double diffclock(clock_t clock1, clock_t clock2) { double diffticks = clock1 - clock2; double diffms = (diffticks) / (CLOCKS_PER_SEC / NUMBER); return diffms; } int main() { // start a timer here clock_t begin = clock(); // execute your functions several times (at least 10'000) for (int i = 0; i < NUMBER; i++) { // a very fast function in the middle func() } // stop timer here clock_t end = clock(); // display results here cout << "Execution time: " << diffclock(end, begin) << " ms." << endl; return 0; }
注意:std :: clock()缺乏足够的精度来进行性能分析.参考.