C库函数clock_t clock(void) 返回自该计划推出以来经过的时钟滴答数。秒使用的CPU的数量,您将需要除以CLOCKS_PER_SEC。
CLOCKS_PER_SEC等于1000000在32位系统中,这个函数将返回相同的值大约每72分钟一次。
声明
以下是clock() 函数的声明。
clock_t clock(void)
参数
-
NA
返回值
这个函数返回程序启动以来经过的时钟滴答数。失败时,函数返回值-1。
例子
下面的例子演示了如何使用clock() 函数。
#include <time.h> #include <stdio.h> int main() { clock_t start_t, end_t, total_t; int i; start_t = clock(); printf("Starting of the program, start_t = %ld ", start_t); printf("Going to scan a big loop, start_t = %ld ", start_t); for(i=0; i< 10000000; i++) { } end_t = clock(); printf("End of the big loop, end_t = %ld ", end_t); total_t = (double)(end_t - start_t) / CLOCKS_PER_SEC; printf("Total time taken by CPU: %f ", total_t ); printf("Exiting of the program... "); return(0); }
让我们编译和运行上面的程序,这将产生以下结果:
Starting of the program, start_t = 0 Going to scan a big loop, start_t = 0 End of the big loop, end_t = 20000 Total time taken by CPU: 0.000000 Exiting of the program...