高分辨率时序部分代码 [英] High Resolution Timing Part of Your Code
本文介绍了高分辨率时序部分代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想测量循环中函数的速度。但是为什么我的做法总是打印0,而不是高分辨率定时与9位十进制精度(即纳米/微秒)?
方法吗?
#include< iomanip>
#include< iostream>
#include< time.h>
int main(){
for(int i = 0; i <100; i ++){
std :: clock_t startTime = std :: clock ();
//中间非常快的函数
cout<< 时间:< setprecision(9)<< (clock() - startTime + 0.00)/ CLOCKS_PER_SEC < endl;
}
return 0;相关问题:
$ b
解决方案将 }
语句然后将总执行时间乘以测试循环中的操作数。
#include < iostream>
#include< ctime>
#define NUMBER 10000 //操作数
//获取开始和结束时间之间的差异并指定
//操作数
double diffclock(clock_t clock1,clock_t clock2)
{
double diffticks = clock1 - clock2;
double diffms =(diffticks)/(CLOCKS_PER_SEC / NUMBER);
return diffms;
}
int main(){
//在这里启动一个定时器
clock_t begin = clock();
//执行你的函数几次(至少10'000)
for(int i = 0; i // a fast函数在中间
func()
}
//停止计时器在这里
clock_t end = clock();
//在此显示结果
cout<< 执行时间:< diffclock(end,begin)<< 女士。 << endl;
return 0;
}
注意:std :: clock()缺少足够的精度。 参考。
I want to measure the speed of a function within a loop. But why my way of doing it always print "0" instead of high-res timing with 9 digits decimal precision (i.e. in nano/micro seconds)?
What's the correct way to do it?
#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;
}
Related Questions:
- How to overcome
clock()
's low resolution
- High Resolution Timer with C++ and linux
- Equivalent of Windows’
QueryPerformanceCounter
on OSX
解决方案 Move your time calculation functions outside for () { .. }
statement then devide total execution time by the number of operations in your testing loop.
#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;
}
Note: std::clock() lacks sufficient precision for profiling. Reference.
这篇关于高分辨率时序部分代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文