环境:
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);
}
结果: