VC/MFC中計算程序/系統運行時間

法一 利用GetTickCount函數 

獲取程序運行時間 

複製代碼
。。。

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

。。。。。。
//to do sth

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

cout
<<t2-t1<<endl;//前後之差即程序運行時間

。。。

複製代碼

 

 

獲取系統運行時間

 

複製代碼
CString str;

//獲取程序運行時間

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

//Sleep(500);

//AfxMessageBox("do something...");

。。。。。。
//to do sth

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

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

AfxMessageBox(str);
複製代碼

 

    

法二 利用C/C++計時函數

 獲取程序運行時間

 

複製代碼
#include "time.h"

。。。

clock_t start, finish;

start
= clock();

。。。。。。
//to do sth

finish
= clock();

//cout<<(double)(finish-start)/CLOCKS_PER_SEC<<" seconds"<<endl;

printf(
"%f seconds\n",(double)(finish-start)/CLOCKS_PER_SEC);



。。。
複製代碼

 

 

函數/參數說明

clock()

C/C++計時函數,與其相關的數據類型是clock_t

返回:從"此程序進程開啓"到"程序中調用clock()函數"之間CPU計時單元數,MSDN中稱掛鐘時間(wal-clock)

clock_t

用來保存時間的數據類型,在time.h中定義:typedef   long   clock_t;  爲長整型

CLOCKS_PER_SEC

用來表示一秒鐘會有多少個時鐘計時單元,在time.h中定義:#define CLOCKS_PER_SEC ((clock_t)1000)  

 

獲取系統運行的時間

 

複製代碼
CString str,str1;

//獲取系統運行時間

long t=GetTickCount();

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);

複製代碼

 

 

 

法三  利用CTime類 獲取系統時間

 

複製代碼
CString str;

//獲取系統時間

CTime tm;

tm
=CTime::GetCurrentTime();

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

AfxMessageBox(str);

複製代碼

 

 

 

法四  利用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);

發佈了74 篇原創文章 · 獲贊 36 · 訪問量 17萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章