linux下统计程序运行时间实例代码

发布时间:2020-01-21编辑:脚本学堂
本文介绍了linux中用c语言实现统计程序运行时间的一段代码,有需要的朋友参考下。

linux 中的 <sys/time.h> 中 有个函数可以获取当前时间,精确到 微秒 ---->  gettimeofday()

例子:
 

复制代码 代码示例:
#include <sys/time.h> 
// int gettimeofday(struct timeval *tv, struct timezone *tz);
    /*********************************************
     * struct timeval
     * {
     *     time_t      tv_sec;   // seconds
     *     suseconds_t tv_usec;  // microseconds:微秒 10^(-6)s, 这里的 tv_sec 用的是 微秒
     *                           // millisecond :毫秒 10^(-3)s
     * }
     **********************************************
     * struct timezone
     * {
     *     int tz_minuteswest;   // minutes west of Greenwich
     *     int tz_dsttime;       // type of DST correction
     * }
     **********************************************/
 

使用时,定义两个 struct timeval  变量(通常 gettimeofday() 的第二个参数 设为 NULL),分别保存 代码测试 前后的时刻,最后相减,即可获取 代码运行时间 (可转换为自己需要的时间)。

例子:
 

复制代码 代码示例:

#include <stdio.h>
#include <sys/time.h> // for gettimeofday()
#include <string.h>   // for memset()

int main()
{
    int i = 10000000;
    struct timeval start, end;  // define 2 struct timeval variables

    //-------------------------
    gettimeofday(&start, NULL); // get the beginning time
    //-------------------------
   
    // test code
    while(i)
    {
        i--;
    }

    //-------------------------
    gettimeofday(&end, NULL);  // get the end time
    //-------------------------
   
    long long total_time = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_usec - start.tv_usec); // get the run time by microsecond
    printf("total time is %lld usn", total_time);
    total_time /= 1000; // get the run time by millisecond
    printf("total time is %lld msn", total_time);
}

测试结果:(centos 6.5, gcc 4.4.7)
total time is 49658 us
total time is 49 ms

测试结果:(CentOS 6.5, gcc 4.4.7)
total time is 49658 us
total time is 49 ms