nev*_*int 7 c++ time high-resolution
我想测量循环中函数的速度.但是为什么我这样做的方式总是打印"0"而不是9位十进制精度(即纳秒/微秒)的高分辨率时序?
这样做的正确方法是什么?
#include <iomanip>
#include <iostream>
#include <time.h>
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;
}
Run Code Online (Sandbox Code Playgroud)
将时间计算函数for () { .. }移到语句之外,然后将总执行时间与测试循环中的操作数分开.
#include <iostream>
#include <ctime>
#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;
}
Run Code Online (Sandbox Code Playgroud)
注意:std :: clock()缺乏足够的精度来进行性能分析.参考.
| 归档时间: |
|
| 查看次数: |
5132 次 |
| 最近记录: |