如何计算和大约打印clock_t时间 [英] How to calculate and print clock_t time roughly

查看:649
本文介绍了如何计算和大约打印clock_t时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在计时需要多长时间来做三种不同类型的搜索,顺序,递归二进制和迭代二进制。我有那些到位,它会循环遍历并完成搜索。我的问题是,当我所有的时间,我得到0为所有的每一次,即使我做一个100,000的数组,我搜索不在数组中的东西。如果我在搜索中设置了一个断点,它显然使得时间更长,它给我一个合理的时间,我可以工作。

I am timing how long it takes to do three different types of searches, sequential, recursive binary, and iterative binary. I have those in place, and it does iterate through and finish the search. My problem is that when I time them all, I get 0 for all of them every time, even if I make an array of 100,000, and I have it search for something not in the array. If I set a break point in the search it obviously makes the time longer, and it gives me a reasonable time that I can work with. But otherwise it is always 0. Here is my code, it is similar for all three search timers.

 clock_t recStart = clock();
 mySearch.recursiveSearch(SEARCH_INT);
 clock_t recEnd = clock();
 clock_t recDiff = recEnd - recStart;
 double recClockTime = (double)recDiff/(double)CLOCKS_PER_SEC;
 cout << recClockTime << endl;

 cout << CLOCKS_PER_SEC << endl;

 cout << recClockTime << endl;

对于最后两个,我得到 1000 0

For the last two I get 1000 and 0.

我在这里做错了吗?或者是在我的搜索对象中?

Am I doing something wrong here? Or is it in my search Object?

推荐答案

clock()不是一个精确的定时器,它只是不能很好地为短时间间隔定时。

clock() is not an accurate timer, and it just don't work well for timing short intervals.

C说时钟返回实现的最佳近似

如果在两个连续的时钟调用之间,程序花费的时间少于一个时钟函数的统一,你可以得到0. POSIX clock 定义与 CLOCKS_PER_SEC 的统一为 1000000 (unity is then 1 microsecond)。

If between two successive clock calls you program takes less time than one unity of the clock function, you could get 0. POSIX clock defines the unity with CLOCKS_PER_SEC as 1000000 (unity is then 1 microsecond).

http://pubs.opengroup.org/onlinepubs/009604499/functions/clock.html

要测量x86 / x64中的时钟周期,可以使用汇编来检索CPU时间戳计数器寄存器 rdtsc 的时钟计数。 (可以通过内联汇编实现?)注意,它返回时间戳,而不是经过的秒数。因此,您还需要检索cpu频率。

To measure clock cycles in x86/x64 you can use assembly to retreive the clock count of the CPU Time Stamp Counter register rdtsc. (which can be achieved by inline assembling?) Note that it returns the time stamp, not the number of seconds elapsed. So you need to retrieve the cpu frequency as well.

但是,获取准确时间的最佳方法取决于您的平台。

However, the best way to get accurate time in seconds depends on your platform.

总而言之,几乎不可能实现计算和打印 clock_t 准确。您可能希望在Stackoverflow上查看 this 以找到更好的方法(如果准确性是最重要的) 。

To sum up, it's virtually impossible to achieve calculating and printing clock_t time in seconds accurately. You might want to see this on Stackoverflow to find a better approach (if accuracy is top priority).

这篇关于如何计算和大约打印clock_t时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆