测试C/C++程序运行时间

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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值