#include <sys/time.h>
int gettimeofday(struct timeval *tv,
struct timezone *tz);
功能:将目前的时间以tv所指的结构返回。
struct timeval{
long tv_sec; //秒
long tv_usec; //微秒
};
============================================================
#include
#include
#include
bool SubTimeval(timeval &result, timeval &begin, timeval
&end)
//
计算gettimeofday函数获得的end减begin的时间差,并将结果保存在result中。
{
if (
begin.tv_sec>end.tv_sec ) return false;
if (
(begin.tv_sec == end.tv_sec) && (begin.tv_usec > end.tv_usec)
)
return false;
result.tv_sec = (
end.tv_sec - begin.tv_sec );
result.tv_usec = ( end.tv_usec -
begin.tv_usec );
if (result.tv_usec<0)
{
result.tv_sec--;
result.tv_usec+=1000000;}
return true;
}
int main(int argc, char **argv)
{
timeval tBegin, tEnd,
tDiff;
gettimeofday(&tBegin, 0);
sleep(3);
// 浪费一下时间看看。:)
gettimeofday(&tEnd, 0);
SubTimeval(tDiff, tBegin, tEnd);
printf("耗时:%d.%d 秒/n",
tDiff.tv_sec, tDiff.tv_usec);
}
//////////////////////////////////////////////////////////////////////////////////
static LONGLONG begin_time, end_time;
static double time_fre, time_elapsed;
static LARGE_INTEGER litmp;
本文介绍了一种使用C++获取系统当前时间并计算两次时间间隔的方法。通过gettimeofday函数获取时间戳,并定义了一个SubTimeval函数来计算两个时间戳之间的差值。此外,还展示了如何利用Windows API函数QueryPerformanceCounter和QueryPerformanceFrequency进行高精度计时。
2万+

被折叠的 条评论
为什么被折叠?



