Chinaunix首页 | 论坛 | 博客
  • 博客访问: 624039
  • 博文数量: 127
  • 博客积分: 6136
  • 博客等级: 准将
  • 技术积分: 1461
  • 用 户 组: 普通用户
  • 注册时间: 2009-10-24 00:32

分类: C/C++

2011-06-13 15:21:15

有时我们需要评价一个算法性能,那么算法的执行时间便是一个不可忽视的因素,而由于某种特殊的需求,我们需要算法的执行时间尽可能地精确,linux下就提供了这样的一个函数:clock_gettime。该函数提供的可是提供了纳秒的精确度。

函数的原型如下:

int clock_gettime(clockid_t clk_id, struct timespect *tp);

clockid_t clk_id用于指定计时时钟的类型,对于我们Programmr以下三种比较常用:

CLOCK_REALTIME, a system-wide realtime clock.
CLOCK_PROCESS_CPUTIME_ID, high-resolution timer provided by the CPU for each process.
CLOCK_THREAD_CPUTIME_ID, high-resolution timer provided by the CPU for each of the threads.
CLOCK_REALTIME, a system-wide realtime clock.
CLOCK_PROCESS_CPUTIME_ID, high-resolution timer provided by the CPU for each process.
CLOCK_THREAD_CPUTIME_ID, high-resolution timer provided by the CPU for each of the threads.
struct timespect *tp用来存储当前的时间,其结构如下:
1 struct timespec {
2 time_t tv_sec; /* seconds */
3 long tv_nsec; /* nanoseconds */
4 };
测试代码:

#include <stdio.h>
#include <time.h>

struct timespec diff(struct timespec start,struct timespec end)
{
    struct timespec temp;
    if((end.tv_nsec-start.tv_nsec)<0)
    {
        temp.tv_sec = end.tv_sec-start.tv_sec-1;
        temp.tv_nsec = 1000000000 + end.tv_nsec-start.tv_nsec;
    }
    else
    {
        temp.tv_sec = end.tv_sec-start.tv_sec;
        temp.tv_nsec = end.tv_nsec-start.tv_nsec;
    }
    return temp;
}

int main()
{
    struct timespec time1,time2,temp;
    int i;
    clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time1);
    for(i=0; i<10000;i++)
    {
        ;
    }
    clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time2);
    temp = diff(time1, time2);
    printf("%d:%d\n", temp.tv_sec, temp.tv_nsec);
    return 0;    
}

这里需要注意一点的就是,编译时需要链接lrt库,否则会提示找不到clock_gettime函数,
[root@localhost ~]# gcc timetest.c -o timetest -lrt
阅读(6891) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~