C语言定时器

环境:
ubuntu16.04 LTS i686
gcc5.4.0

我们在写C程序的时候往往需要衡量一段代码的执行时间,方便程序的优化。所以我们需要写一个定时器程序。POSIX.1-2001提供了gettimeofday()函数可以用来获得系统相对于Epoch(1970-01-01 00:00:00 UTC) 的时间(微秒),POSIX.1-2008废弃了gettimeofday(),建议大家用clock_gettime()(纳秒)。我认为之所以废弃是因为clock_gettime()不仅提高了精度,而且提供了更加丰富的时间获取方法,尤其是可以避免settimeofday()或者clock_settime()改变系统时间。下面是我实现的定时器供参考。

timer.h

double xu_wallclock(void);

#define MAX_RUNTIME -10*365*365*24*60*60.0 /** Timing will fail if execution takes longer than 10 years */
#define timer_clear(tmr) (tmr = 0.0)
#define timer_start(tmr) do {if(tmr > MAX_RUNTIME){tmr -= xu_wallclock();}} while(0)
#define timer_stop(tmr) do {if(tmr < MAX_RUNTIME){tmr += xu_wallclock();}} while(0)
~                                                                       

timer.c

#include <stddef.h>
#include <time.h>
#include <sys/time.h>

double xu_wallclock1(void)
{
#ifdef __GNUC__
    struct timeval ctime;

    gettimeofday(&ctime, NULL);

    return (1.0e+6 * (double)ctime.tv_sec + (double)ctime.tv_usec);
#else
    return (double)time(NULL);
#endif
}

double xu_wallclock(void)
{
#ifdef __GNUC__
    struct timespec ctime;
    int error;

    error = clock_gettime(CLOCK_MONOTONIC_RAW, &ctime);

    return (1.0e+9 * (double)ctime.tv_sec + (double)ctime.tv_nsec);
#else
    return (double)time(NULL);
#endif
}

try.c

#include <stdio.h>
#include "timer.h"

int main()
{
    double timer;
    int t;

    t = 0;
    timer = 0.0;
    timer_start(timer);
    while(t < 1000)
    {
        t++;
    }
    timer_stop(timer);
    printf("timeflash:%.2lfns\n", timer);
}

结果:
这里写图片描述

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值