当前位置 - 股票行情交易網 - 財經新聞 - C++中如何精確計時

C++中如何精確計時

下面是我以前找的些資料。

1.使用CTime類

CString str;

//獲取系統時間

CTime tm;

tm=CTime::GetCurrentTime();

str=tm.Format("現在時間是%Y年%m月%d日 %X");

MessageBox(str,NULL,MB_OK);

2: 得到系統時間日期(使用GetLocalTime)

SYSTEMTIME st;

CString strDate,strTime;

GetLocalTime(&st);

strDate.Format("%4d-%2d-%2d",st.wYear,st.wMonth,st.wDay);

strTime.Format("%2d:%2d:%2d",st.wHour,st.wMinute,st.wSecond);

AfxMessageBox(strDate);

AfxMessageBox(strTime);

3.使用GetTickCount

//獲取程序運行時間

long t1=GetTickCount();//程序段開始前取得系統運行時間(ms)

Sleep(500);

long t2=GetTickCount();();//程序段結束後取得系統運行時間(ms)

str.Format("time:%dms",t2-t1);//前後之差即 程序運行時間

AfxMessageBox(str);

//獲取系統運行時間

long t=GetTickCount();

CString str,str1;

str1.Format("系統已運行 %d時",t/3600000);

str=str1;

t%=3600000;

str1.Format("%d分",t/60000);

str+=str1;

t%=60000;

str1.Format("%d秒",t/1000);

str+=str1;

AfxMessageBox(str);

用VC++獲取系統時間幾種方法

用VC++獲取系統時間幾種方法

Q:如何獲取時間?精度如何?

A:

1 使用time_t time( time_t * timer ) 精確到秒

計算時間差使用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() 精確到秒

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++怎樣獲取系統時間,返回值是什麽類型的變量呢?

GetSystemTime返回的是格林威誌標準時間

GetLocalTime,和上面用法壹樣,返回的是妳所在地區的時間,中國返回的是北京時間

VOID GetSystemTime(

LPSYSTEMTIME lpSystemTime // address of system time structure

);

函數就可以獲得了,其中LPSYSTEMTIME 是個結構體

含:年,月,日,周幾,小時,分,秒,毫秒。

LARGE_INTEGER litmp;

LONGLONG QPart1,QPart2;

double dfMinus, dfFreq, dfTim;

QueryPerformanceFrequency(&litmp);

dfFreq = (double)litmp.QuadPart;// 獲得計數器的時鐘頻率

QueryPerformanceCounter(&litmp);

QPart1 = litmp.QuadPart;// 獲得初始值

do

{

QueryPerformanceCounter(&litmp);

QPart2 = litmp.QuadPart;//獲得中止值

dfMinus = (double)(QPart2-QPart1);

dfTim = dfMinus / dfFreq;// 獲得對應的時間值,單位為秒

}while(dfTim<0.001);