缺点:精度不够高,不能用于程序运行持续时间小于100ms的测量。
优点:准确性不是十分依赖于系统负载,并且在执行时间大于1s的程序上,与理论值之间的误差很低。
方法:在程序开始时读取计时器的内容,在程序终止前再次读取Timer的内容。主要的接口函数有:
Unix/Linux:
clock_t times(struct tms *buf);
//return value:系统自启动以来经过的时间滴答数,常数CLK_TCK表示每秒经过的时钟滴答数
//parameter:一个指向tms结构的指针
//使用该函数时要包含头文件<sys/times.h>
Win32:
DWORD GetTickCount(VOID)
//return value:the number of milliseconds that have elapsed since the system was started.
//使用时应包含<windows.h>,link阶段应链接 kernel32.lib
Calculates the wall-clock time used by the calling process.
clock_t clock( void );
Return Value
The elapsed wall-clock time since the start of the process (elapsed time in seconds times CLOCKS_PER_SEC). If the amount of elapsed time is unavailable, the function returns –1, cast as a clock_t.
Example
// crt_clock.c
/* This example prompts for how long
* the program is to run and then continuously
* displays the elapsed time for that period.
*/
int main( void )
{
long i = 6000000L;
clock_t start, finish;
double duration;
/* Delay for a specified time. */
printf( "Delay for three seconds\n" );
sleep( (clock_t)3 * CLOCKS_PER_SEC );
printf( "Done!\n" );
/* Measure the duration of an event. */
printf( "Time to do %ld empty loops is ", i );
start = clock();
while( i-- )
;
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
printf( "%2.1f seconds\n", duration );
}
/* Pauses for a specified number of milliseconds. */
void sleep( clock_t wait )
{
clock_t goal;
goal = wait + clock();
while( goal > clock() )
;
}
Sample Output
Delay for three seconds
Done!
Time to do 6000000 empty loops is 0.1 seconds