Home C&C++函数库 c++ 语法 程序源码 Linux C库

clock

函数   <ctime>

clock_t clock (void);

时钟程序

返回程序消耗的处理器时间。

返回的值以时钟滴答声(clock ticks)表示,时钟滴答声是一个常量的时间单位, 但是特定于系统的长度(参考CLOCKS_PER_SEC每秒滴答声)。

时钟引用的时间在不同系统之间是不同的,但它与程序的执行 (通常是程序的启动)有关。

要计算程序的实际处理时间, 必须将时钟返回的值与之前调用同一函数返回的值进行比较。

☲  参数


none

☉  返回值



程序执行所用的时钟滴答数。

如果失败,函数将返回-1的值。

clock_t是在 <ctime>中定义的类型,作为基本算术类型的别名。

☣  示例



/* 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++)



无抛出保证:此函数从不抛出异常。

🍄  另请参阅



time 获取当前时间(function)
difftime 返回两次之间的差值(function)

联系我们 免责声明 关于CandCplus 网站地图