C语言 <time.h> clock 函数

  • 描述

    C库函数clock_t clock(void)返回自程序启动以来经过的时钟滴答数。要获得CPU使用的秒数,您需要除以CLOCKS_PER_SEC。在CLOCKS_PER_SEC等于1000000的32位系统上,此函数大约每72分钟将返回相同的值。
  • 声明

    以下是clock函数的声明。
    
    clock_t clock(void)
    
    参数
    没有参数。
  • 返回值

    此函数返回自程序启动以来经过的时钟滴答数。失败时,该函数返回值-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\n", start_t);
        
       printf("Going to scan a big loop, start_t = %ld\n", start_t);
       for(i=0; i< 10000000; i++) {
       }
       end_t = clock();
       printf("End of the big loop, end_t = %ld\n", end_t);
       
       total_t = (double)(end_t - start_t) / CLOCKS_PER_SEC;
       printf("Total time taken by CPU: %f\n", total_t  );
       printf("Exiting of the program...\n");
    
       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...