函式
<ctime>

clock

clock_t clock (void);
時鐘程式
返回程式消耗的處理器時間。

返回的值以時鐘週期(clock ticks)表示,這是一個恆定但系統特定的時間單位(每秒有 CLOCKS_PER_SEC時鐘週期)。

clock 用作參考的紀元(epoch)因系統而異,但它與程式的執行相關(通常是其啟動時間)。要計算程式的實際處理時間,應將 clock 返回的值與先前呼叫同一函式返回的值進行比較。

引數



返回值

自與特定程式執行相關的某個紀元以來經過的時鐘週期數。

失敗時,該函式返回 -1

clock_t 是在 <ctime> 中定義的一種型別,作為基本算術型別的別名。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/* clock example: frequency of primes */
#include <stdio.h>      /* printf */
#include <time.h>       /* clock_t, clock, CLOCKS_PER_SEC */
#include <math.h>       /* sqrt */

int frequency_of_primes (int n) {
  int i,j;
  int freq=n-1;
  for (i=2; i<=n; ++i) for (j=sqrt(i);j>1;--j) if (i%j==0) {--freq; break;}
  return freq;
}

int main ()
{
  clock_t t;
  int f;
  t = clock();
  printf ("Calculating...\n");
  f = frequency_of_primes (99999);
  printf ("The number of primes lower than 100,000 is: %d\n",f);
  t = clock() - t;
  printf ("It took me %d clicks (%f seconds).\n",t,((float)t)/CLOCKS_PER_SEC);
  return 0;
}

輸出

Calculating...
The number of primes lower than 100,000 is: 9592
It took me 143 clicks (0.143000 seconds).


資料競爭

併發呼叫此函式是安全的,不會導致資料競爭。

異常 (C++)

無異常保證:此函式從不丟擲異常。

另見