以微秒为单位计时函数

发布于 2025-01-08 08:43:16 字数 557 浏览 0 评论 0原文

大家好,我正在尝试以微秒为单位计算我编写的一些搜索函数的时间,并且需要足够长的时间才能使其显示 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

情域 2025-01-15 08:43:16

您在这一行中使用整数除法:

int time = (stop - start)/CLOCKS_PER_SEC;

我建议使用 doublefloat 类型,并且您可能需要转换除法的组件。

You are using integer division on this line:

int time = (stop - start)/CLOCKS_PER_SEC;

I suggest using a double or float type, and you'll likely need to cast the components of the division.

捎一片雪花 2025-01-15 08:43:16

使用 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文