以微秒为单位计时函数
大家好,我正在尝试以微秒为单位计算我编写的一些搜索函数的时间,并且需要足够长的时间才能使其显示 2 位有效数字。我编写了这段代码来计时我的搜索功能,但它似乎运行得太快了。我总是得到 0 微秒,除非我运行搜索 5 次然后得到 1,000,000 微秒。我想知道我是否在数学上错误地得到了以微秒为单位的时间,或者是否有某种格式化函数可以用来强制它显示两个数字?
clock_t start = clock();
index = sequentialSearch.Sequential(TO_SEARCH);
index = sequentialSearch.Sequential(TO_SEARCH);
clock_t stop = clock();
cout << "number found at index " << index << endl;
int time = (stop - start)/CLOCKS_PER_SEC;
time = time * SEC_TO_MICRO;
cout << "time to search = " << time<< endl;
Hey guys I'm trying to time some search functions I wrote in microseconds, and it needs to take long enough to get it to show 2 significant digits. I wrote this code to time my search function but it seems to go too fast. I always end up getting 0 microseconds unless I run the search 5 times then I get 1,000,000 microseconds. I'm wondering if I did my math wrong to get the time in micro seconds, or if there's some kind of formatting function I can use to force it to display two sig figs?
clock_t start = clock();
index = sequentialSearch.Sequential(TO_SEARCH);
index = sequentialSearch.Sequential(TO_SEARCH);
clock_t stop = clock();
cout << "number found at index " << index << endl;
int time = (stop - start)/CLOCKS_PER_SEC;
time = time * SEC_TO_MICRO;
cout << "time to search = " << time<< endl;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您在这一行中使用整数除法:
我建议使用
double
或float
类型,并且您可能需要转换除法的组件。You are using integer division on this line:
I suggest using a
double
orfloat
type, and you'll likely need to cast the components of the division.使用 QueryPerformanceCounter 和 QueryPerformanceFrequency,假设您在 Windows 平台上,
这里有一个指向 ms KB 如何使用 QueryPerformanceCounter 来计时代码
Use QueryPerformanceCounter and QueryPerformanceFrequency, assuming your on windows platform
here a link to ms KB How To Use QueryPerformanceCounter to Time Code