clock

計算所呼叫的處理序使用的時鐘時間。

語法

clock_t clock( void );

傳回值

啟動處理序時自 CRT 初始化以來已耗用的時間 (測量單位:每秒 CLOCKS_PER_SEC 單位數)。 如果已耗用時間無法使用,或已超過可記錄為 clock_t 類型的最大正時間,則此函式會傳回值 (clock_t)(-1)

備註

clock 函式會告知在處理序啟動期間自 CRT 初始化之後已使用多少時鐘時間。 此函式不符合 ISO C,它會將淨 CPU 時間指定為傳回值。 若要取得 CPU 時間,請使用 Win32 GetProcessTimes 函式。 若要判定已耗用時間 (秒),請將 clock 函式所傳回的值除以巨集 CLOCKS_PER_SEC

只要有足夠的時間,clock 所傳回的值可能會超過 clock_t 的最大正值。 處理序執行時間較久時,clock 所傳回的值一律為 ISO C99 標準 (7.23.2.1) 和 ISO C11 標準 (7.27.2.1) 所指定的 (clock_t)(-1)。 Microsoft 會將 clock_t 實作為 long (帶正負號的 32 位元整數),而且 CLOCKS_PER_SEC 巨集定義為 1000。 此宏會提供最大 clock 函式傳回值 2147483.647 秒,或大約 24.8 天。 請勿依賴在執行時間超過此時間量之進程中傳 clock 回的值。 您可以使用 64 位 time 函式或 Windows QueryPerformanceCounter 函式來記錄經過多年的進程時間。

需求

常式 必要的標頭
clock <time.h>

如需相容性詳細資訊,請參閱相容性

範例

// crt_clock.c
// This sample uses clock() to 'sleep' for three
// seconds, then determines how long it takes
// to execute an empty loop 600000000 times.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

// Pauses for a specified number of clock cycles.
void do_sleep( clock_t wait )
{
   clock_t goal;
   goal = wait + clock();
   while( goal > clock() )
      ;
}

const long num_loops = 600000000L;

int main( void )
{
   long    i = num_loops;
   clock_t start, finish;
   double  duration;

   // Delay for a specified time.
   printf( "Delay for three seconds\n" );
   do_sleep( (clock_t)3 * CLOCKS_PER_SEC );
   printf( "Done!\n" );

   // Measure the duration of an event.
   start = clock();
   while( i-- )
      ;
   finish = clock();
   duration = (double)(finish - start) / CLOCKS_PER_SEC;
   printf( "Time to do %ld empty loops is ", num_loops );
   printf( "%2.3f seconds\n", duration );
}
Delay for three seconds
Done!
Time to do 600000000 empty loops is 1.354 seconds

另請參閱

時間管理
difftime, _difftime32, _difftime64
time, _time32, _time64