利用gettimeofday简单测试程序用时

来源:互联网 发布:量子计算机人工智能股 编辑:程序博客网 时间:2024/06/05 03:39
centos$ man 2 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};// it gives the number of seconds and microseconds since the Epoch (see time(2))struct timezone {    int tz_minuteswest; //minutes west of Greenwich    int tz_dsttime;    //type of DST correction};// if tv or tz is NULL, the corresponding structure is no set or returned.

简单测试用例

程序中添加两个struct timeval 来记录开始和完成的时间就可以了。

#include <stdio.h>#include <stdlib.h>#include <sys/time.h>int main(){    struct timeval beginTime, endTime;    if (gettimeofday(&beginTime, NULL) == -1)        return -1;    for (int i = 1; i <= 10000; i++)        for (int j = 1; j <= 10000; j++)            ;    if (gettimeofday(&endTime, NULL) == -1)        return -1;    double seconds;    seconds = 1000000*(endTime.tv_sec - beginTime.tv_sec) + (endTime.tv_usec - beginTime.tv_usec);    seconds /= 1000000;    printf("using time : %f\n", seconds);    return 0;}

运行结果

这里写图片描述

0 0
原创粉丝点击