打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
程序计时:clock
    有时我们需要评价一个算法性能,那么算法的执行时间便是一个不可忽视的因素,而由于某种特殊的需求,我们需要算法的执行时间尽可能地精确,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
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
clock get ns
linux下常用的几个时间函数:time,gettimeofday,clock
Linux下如何计算函数的执行时间?实例代码直接拿去用
timerfd使用总结
Linux时间子系统之三:时间的维护者:timekeeper
linux时间函数
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服