C++ clock() function 問題

2009-01-14 6:12 pm
如果要測知一個function 的運行速度,很多人都會用clock() :
clock_t start = clock();
test_function();
clock_t end = clock();
double time_need = (end-start)*1.0/CLOCKS_PER_SEC;

可是我使用這方法時,當time_need 的預期值超過一小時時,所計出的time_need 竟是負數,為甚麼?

有辦法解決嗎?

回答 (1)

2009-01-15 7:51 pm
✔ 最佳答案
clock() returns the number of clock-ticks since program start. Since you may have executed other things before the test-Function(), you have correctly inserted a call to clock() and called the reference time start.
A negative value could mean two things:
1. The clock() function encountered a problem and returns a -1.
2. There is an overflow in the calculation of the time difference, i.e. start or end exceeds the capacity of the clock_t type.
The clock_t type is mostly platform dependent. It is usually typedef'd as a long integer, so it can accomodate (in most cases) minimum of 2147483647 ticks for a 32 bit variable.
The number of ticks defined for Dev C++ is 1000, which means that the precision of the measure is one milliseconds.
If you print CLOCKS_PER_SEC using a %ld format, you will see what the multiplier is, and find out if 3600 seconds (one -hour) will cause an overflow to the long integer on your system.
If the problem persists, print all the intermediate values and see if it will give you more information.

If everything fails, you can pass "start" into the test function and print the progress from time to time (before the overflow occurs).

2009-01-24 02:17:33 補充:
Try to print the individual values of start, end and CLOCKS_PER_SECOND in order to find out the source of the problem.

2009-01-24 02:17:51 補充:
If the program is executed just before mid-night (according to the computer clock), it will be a negative number, or a huge number. If CLOCKS_PER_SECOND is zero or undefined, it will cause an overflow.

2009-01-24 02:17:58 補充:
Please PM me with the name of the compiler, and the above values when you execute, and also find out the wall clock time (from you watch) if possible.

2009-01-24 02:23:07 補充:
You can also use difftime() to calculate the elapsed time, but the resolution is only about 1 second. If it is a complex calculation that takes hours or minutes to do, it would be OK. See following link for an example:
http://www.cplusplus.com/reference/clibrary/ctime/difftime.html


收錄日期: 2021-04-13 16:22:05
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20090114000051KK00265

檢視 Wayback Machine 備份