How to calculate and print clock_t time roughly

偶尔善良 提交于 2019-12-11 13:36:15

问题


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;

For the last two I get 1000 and 0.

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


回答1:


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

C says clock returns the implementation’s best approximation to the processor time used by the program since the beginning of an implementation-defined era related only to the program invocation.

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)

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.


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).




回答2:


clock() just doesn't have enough resolution - here is one good discussion/blog on that topic http://www.guyrutenberg.com/2007/09/10/resolution-problems-in-clock/

I think two options either use clock_gettime or even better have you considered using OProfile or CodeAnalyst?

I personally prefer to use tools - OProfile is good. I have not used CodeAnalyst before - and then there is Valgrind and gprof.

If you insist on using clock_gettime - please check this out http://www.guyrutenberg.com/2007/09/22/profiling-code-using-clock_gettime/



来源:https://stackoverflow.com/questions/14917405/how-to-calculate-and-print-clock-t-time-roughly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!