1 简介
实践中经常会遇到统计或测试一段程序或算法的执行时间,笔者在linux下使用宏定义的方式编写了如下自定义的头文件来完成统计运行时间的功能并实现了一个类似于sleep功能的毫秒级delay程序,对于时间精度要求更高的统计场景此方式暂且难以胜任。
2 timer.h
/* By caft... ^!~
This head file is used to "count" time.
There are some macro can be used for counting
the run-time of some expressions.
@Author: caft0505@gmail.com
*/
#ifndef _TIMER_H_
#define _TIMER_H_
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/select.h>
// Define the type of unit to get result.
typedef enum
{
TIMER_UNIT_USEC = 1,
TIMER_UNIT_MSEC = 1000,
TIMER_UNIT_SEC = 1000000
}TIMER_UNIT;
// This global variable is used for different result.
TIMER_UNIT _UNIT = TIMER_UNIT_MSEC
// Set the global variable unit.
#define TIMER_UNIT_SET(unit) {_UNIT = unit;}
#define TIMER_T struct timeval
// Get value of the microseconds of the timer.
//#define TIMER_VAL(timer) (timer.tv_usec)
// Get current time.
#define TIMER_GET(timer) \
{\
if(-1 == gettimeofday(&timer, NULL) )\
{\
perror("gettimeofday");\
exit