#ifdef DEBUG_CODES_TIME
void timer_start(timespec *aStartTime)
{
clock_gettime(CLOCK_REALTIME, aStartTime);
}
long timer_end(timespec *aStartTime)
{
timespec endTime;
clock_gettime(CLOCK_REALTIME, &endTime);
long totalTimeMs = (endTime.tv_sec * 1000 + endTime.tv_nsec / 1000000) - (aStartTime->tv_sec * 1000 + aStartTime->tv_nsec / 1000000);
return totalTimeMs;
}
clock_t _timing_clock = 0;
void timer_handler(int sig)
{
_timing_clock = clock();
}
__attribute((constructor)) void timing_init()
{
signal(SIGALRM, timer_handler);
struct itimerval tick;
memset(&tick, 0, sizeof(tick));
tick.it_value.tv_usec = 1;
tick.it_interval.tv_usec = 10000; //微秒
setitimer(ITIMER_REAL, &tick, NULL);
printf("(debug) initialize timing clock to %f seconds\n", tick.it_interval.tv_usec / 1000000.0);
}
#else
#define timer_start(ts)
#define timer_end(ts) -1
#endif
int main()
{
timespec ts;
timer_start(&ts);
for(int i=0; i<1000000; ++i);
long ret = timer_end(&ts);
printf("Result: %ld \n",ret);
return 0;
$./a.out
(debug) initialize timing clock to 0.010000 seconds
$./a.out
Result: -1
void timer_start(timespec *aStartTime)
{
clock_gettime(CLOCK_REALTIME, aStartTime);
}
long timer_end(timespec *aStartTime)
{
timespec endTime;
clock_gettime(CLOCK_REALTIME, &endTime);
long totalTimeMs = (endTime.tv_sec * 1000 + endTime.tv_nsec / 1000000) - (aStartTime->tv_sec * 1000 + aStartTime->tv_nsec / 1000000);
return totalTimeMs;
}
clock_t _timing_clock = 0;
void timer_handler(int sig)
{
_timing_clock = clock();
}
__attribute((constructor)) void timing_init()
{
signal(SIGALRM, timer_handler);
struct itimerval tick;
memset(&tick, 0, sizeof(tick));
tick.it_value.tv_usec = 1;
tick.it_interval.tv_usec = 10000; //微秒
setitimer(ITIMER_REAL, &tick, NULL);
printf("(debug) initialize timing clock to %f seconds\n", tick.it_interval.tv_usec / 1000000.0);
}
#else
#define timer_start(ts)
#define timer_end(ts) -1
#endif
int main()
{
timespec ts;
timer_start(&ts);
for(int i=0; i<1000000; ++i);
long ret = timer_end(&ts);
printf("Result: %ld \n",ret);
return 0;
}
调试版:
$g++ test_timer.c -DDEBUG_CODES_TIME -lrt$./a.out
(debug) initialize timing clock to 0.010000 seconds
Result: 4
发布版:
$g++ test_timer.c -lrt$./a.out
Result: -1