计时器

用于给某一段代码计时的代码 

#define START start_watch(&a1);
#define END end_watch(&a2);\
    printf("%s:%s:[%d]:totally time used:[%f]ms\n", __FILE__, __FUNCTION__, __LINE__, show_watch_result(&a1, &a2));

static struct timeval a1,a2; 

static int start_watch(struct timeval *pstart)
{
    int ret = 0;
    ret = gettimeofday(pstart,NULL);
    if (ret != 0) {
        perror("gettimeofday at start");
        return -1;
    }
    return 0;
}

static int end_watch(struct timeval *pend)
{
    int ret = 0;
    ret = gettimeofday(pend, NULL);
    if (ret != 0) {
        perror("gettimeofday at end");
        return -1;
    }
    return 0;
}

static double show_watch_result(struct timeval *pstart, struct timeval *pend)
{
    double time_used;
    time_used = (double)1000000.0*(pend->tv_sec - pstart->tv_sec) + pend->tv_usec - pstart->tv_usec;
    time_used /= (double)1000.0; //精度是ms,毫秒。
    return time_used;
}

 使用举例:

int main()
{
    int i = 10000;
    
    START
    while(i--);
    END
   
    return 0;
}

就会打印出耗时为多少毫秒了。

 

 

 

 

 

你可能感兴趣的:(计时器)