欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  科技

程序运行时间测试 - 使用libc 中 clock 函数

程序员文章站 2022-05-29 09:57:51
我们运行程序的时候,可以简单使用clock函数测试程序的运行时间:(本示例中以微秒为单位输出) https://github.com/yaowenxu/Workplace/blob/master/timer/clocktimer.c 保持更新,更多文章,请关注cnblogs.com/xuyaowen ......

我们运行程序的时候,可以简单使用clock函数测试程序的运行时间:(本示例中以微秒为单位输出)

https://github.com/yaowenxu/workplace/blob/master/timer/clocktimer.c

/**
 * author: yaowen xu
 * github: https://github.com/yaowenxu
 * organization: 北航系统结构研究所
 * date: 2019-08-18 11:59:54
 * lastedittime: 2019-08-18 12:45:45
 * description: 使用 c 语言标准库函数clock来进行测试程序运行时间
 */
#include <time.h>
#include <stdio.h>
#include <math.h>

int str2int(char* str){
    char *p = str;
    int sum = 0;
    while (*p != '\0')
    {
        sum = sum*10 + (*p-'0');
        p++;
    }
    return sum;
}

int main(int argc, char* argv[]){
    clock_t start, stop;
    int def = 1000;
    if (argc == 2)
    {
        def = str2int(argv[argc-1]);
    }
    start = clock();
    for (int i = 0; i < def ; i++)
    {
        float tmp = sqrt(i);
    }
    stop =  clock();
    double total =  stop - start; // 使用运行的时间
    printf("clocks: %.1f\n", total); // 总共使用的时钟
    printf("time: %.1f us\n", total*1e6/(clocks_per_sec)); // 转换运行时间为微秒
    return 0;
}

/*
 * approximates the processor time used by the program, 
 * since the beginning of an implementation-defined time 
 * period that is related to the program invocation. 
 * to measure the time spent in a program, call the clock() 
 * function at the start of the program, and subtract its 
 * returned value from the value returned by subsequent calls 
 * to clock(). then, to obtain the time in seconds, divide 
 * the value returned by clock() by clocks_per_sec.
 * 
 * if you use the system() function in your program, do not 
 * rely on clock() for program timing, because calls to system() 
 * may reset the clock.
 * 
 * in a multithread posix c application, if you are creating threads 
 * with a function that is based on a posix.4a draft standard, 
 * the clock() function is thread-scoped.
 * 
 * refer:https://www.ibm.com/support/knowledgecenter/en/ssltbw_2.3.0/com.ibm.zos.v2r3.bpxbd00/clock.htm
*/

保持更新,更多文章,请关注cnblogs.com/xuyaowen