精确到秒
计算时间差使用double difftime( time_t timer1, time_t timer0 )
2 使用clock_t clock()
得到的是CPU时间 精确到1/CLOCKS_PER_SEC秒
3 使用DWORD GetTickCount() 得到的是系统运行的时间 精确到毫秒
4 如果使用MFC的CTime类,可以用CTime::GetCurrentTime() 精确到秒
CTime time =
CTime::GetCurrentTime(); ///构造CTime对象
int m_nYear =
time.GetYear(); ///年
int m_nMonth =
time.GetMonth(); ///月
int m_nDay =
time.GetDay(); ///日
int m_nHour =
time.GetHour(); ///小时
int m_nMinute =
time.GetMinute(); ///分钟
int m_nSecond =
time.GetSecond(); ///秒
我们还可以用CTime::Format函数将CTime对象转换为字符串对象
例如:
CString m_strTime = time.Format("%Y-%m-%d
%H:%M:%S");
运行结果:
m_strTime为 2001-8-1 12:11:05
5 要获取高精度时间,可以使用
BOOL QueryPerformanceFrequency(LARGE_INTEGER
*lpFrequency)获取系统的计数器的频率
BOOL QueryPerformanceCounter(LARGE_INTEGER
*lpPerformanceCount)获取计数器的值
然后用两次计数器的差除以Frequency就得到时间。
6 还有David的文章中提到的方法:
Multimedia Timer Functions
The following functions are used with multimedia
timers.
timeBeginPeriod/timeEndPeriod/timeGetDevCaps/timeGetSystemTime
timeGetTime/timeKillEvent/TimeProc/timeSetEvent 精度很高
Q:
GetTickCount()函数,说是毫秒记数,是真的吗,还是精确到55毫秒?
A:
GetTickCount()和GetCurrentTime()都只精确到55ms(1个tick就是55ms)。如果要精确到毫秒,应该使用timeGetTime函数或QueryPerformanceCounter函数。具体例子可以参考QA001022
"VC++中使用高精度定时器"、QA001813 "如何在Windows实现准确的定时"和QA004842
"timeGetTime函数延时不准"。
Q:
vc++怎样获取系统时间,返回值是什么类型的变量呢?
A:
GetSystemTime返回的是格林威志标准时间
GetLocalTime,和上面用法一样,返回的是你所在地区的时间,中国返回的是北京时间
VOID GetSystemTime(
LPSYSTEMTIME
lpSystemTime // address of system time structure
);
用法:
SYSTEMTIME ti;
GetSystemTime(&ti);
函数就可以获得了,其中LPSYSTEMTIME 是个结构体
含:年,月,日,周几,小时,分,秒,毫秒。
typedef struct _SYSTEMTIME
{
WORD
wYear;
WORD
wMonth;
WORD
wDayOfWeek;
WORD
wDay;
WORD
wHour;
WORD
wMinute;
WORD
wSecond;
WORD
wMilliseconds;
}
SYSTEMTIME, *PSYSTEMTIME;
------------------------------------------------------------
// QueryPerformanceFrequency 及 QueryPerformanceCounter 实例
//ElapsedTime.h
#ifndef _ELAPSED
#define _ELAPSED
class CElapsed
{
private:
int Initialized;
_int64 Frequency;
_int64 BeginTime;
public:
CElapsed();
bool Begin();
double End(); //停止计数
bool Available();//是否可调用这两个函数
_int64 GetFreq();
};
#endif
//ElapsedTime.cpp
//另外gettickcount()这个函数也是可以精确到ms的
#include
#include "ElapsedTime.h"
CElapsed::CElapsed()
{
Initialized=QueryPerformanceFrequency((LARGE_INTEGER
*)&Frequency);
}
bool CElapsed:: Begin()
{
if(!Initialized)
return 0;
//某些CPU不运行此函数调用
return QueryPerformanceCounter((LARGE_INTEGER
*)&BeginTime);
}
double CElapsed::End() //停止计数
{
if(!Initialized)
return 0.0;
//某些CPU不运行此函数调用
_int64 endtime;
QueryPerformanceCounter((LARGE_INTEGER
*)&endtime);
_int64 elapsed=endtime-BeginTime;
return (double)elapsed/(double)Frequency;
}
bool CElapsed::Available()//是否可调用这两个函数
{
return Initialized;
}
_int64 CElapsed::GetFreq()
{
return Frequency;
}