设为首页 加入收藏

TOP

C/C++ 获取时间间隔的方法
2014-11-24 13:10:00 】 浏览:9258
Tags:C/C 获取 时间 间隔 方法

clock函数方式


Linux平台下C/C++中获取时间间隔的方法,一种比较普遍的认识是采用clock函数




Returns the number of clock ticks elapsed since the program was launched.

The macro constant expression CLOCKS_PER_SEC specifies the relation between a clock tick and a second (clock ticks per second).

The initial moment of reference used by clock as the beginning of the program execution may vary between platforms. To calculate the actual processing times of a program, the value returned by clock should be compared to a value returned by an initial call to clock.


通过两次调用clock函数可以得到起始时间和结束时间,从而得到毫秒级的时间差




gettimeofday函数方式


C/C++语言中有个timeva l结构是可以精确到毫秒,可以利用timeva l来记录起始时间和结束时间


通过调用gettimeofday函数可以得到用timeva l结构记录的当前时间


int gettimeofday(struct timeva l *tv, struct timezone *tz);




具体实现


#include


#include


class ClockTool
{
public:
ClockTool()
: m_begin(0), m_end(0)
{
}



inline void begin()
{
m_begin = clock();
}



inline void end()
{
m_end = clock();
}



inline void reset()
{
m_begin = 0;
m_end = 0;
}



float getInterval()
{
if (m_end < m_begin)
{
return 0;
}
return (double)(m_end - m_begin)/CLOCKS_PER_SEC;
}



private:
clock_t m_begin;
clock_t m_end;
};



class TimeTool
{
public:
TimeTool()
{
reset();
}



inline void begin()
{
gettimeofday(&m_begin, NULL);
}



inline void end()
{
gettimeofday(&m_end, NULL);
}



inline void reset()
{
memset(&m_begin, 0, sizeof(struct timeva l));
memset(&m_end, 0, sizeof(struct timeva l));
}



float getInterval()
{
if (m_end.tv_usec < m_begin.tv_usec)
{
m_end.tv_usec += 1000;
m_end.tv_sec = m_end.tv_sec - 1;
}
return (m_end.tv_sec - m_begin.tv_sec) + (m_end.tv_usec - m_begin.tv_usec) / 1000000.0;
}



private:
struct timeva l m_begin;
struct timeva l m_end;
};


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Java执行Linux命令并返回命令结果 下一篇Android教程:使用Bundle在Activi..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目