c++計算代碼執行時間的方法,毫秒級

來源:互聯網
上載者:User

方法一、

#include<iosteam>
#include<ctime>
using namespace std;
class CTimer
{
public:
CTimer()
{
_start=clock();
}

~CTimer()
{
_end=clock();
cout<< float(_end - _start) / CLK_TCK <<endl;
}
private:
clock_t _start;
clock_t _end;
};

void main()
{
    CTimer t;
    //程式執行部分!
}

 

 

方法二:

//在windows下實現(毫秒級):

DWORD dwStart = GetTickCount(); //取windows啟動到現在的流逝時間(毫秒)
Run_Your_Func(...); //運行你的函數
DWORD dwUsed = GetTickCount() - dwStart; //計算該函數所消耗的時間

方法三:

這比微秒還准!依賴於你的處理器!!!

class CTimer
{
public:
CTimer()
{
QueryPerformanceFrequency(&m_Frequency);
Start();
}
void Start()
{
QueryPerformanceCounter(&m_StartCount);
}
double End()
{
LARGE_INTEGER CurrentCount;
QueryPerformanceCounter(&CurrentCount);
return double(CurrentCount.LowPart - m_StartCount.LowPart) / (double)m_Frequency.LowPart;
}
void ShowNow()
{
LARGE_INTEGER CurrentCount;
QueryPerformanceCounter(&CurrentCount);
cout<<"Timer Count is:"<<double(CurrentCount.LowPart - m_StartCount.LowPart) / (double)m_Frequency.LowPart<<endl;
}
private:
LARGE_INTEGER m_Frequency;
LARGE_INTEGER m_StartCount;
};

下面是你的程式,比如:

int a;
for ( int i = 0; i < 10000;, i++ )
    a++;

你想測它的時間的話這樣寫:

CTimer t;

int a;
for ( int i = 0; i < 10000;, i++ )
    a++;

cout<<"用時"<<t.end()<<"秒"<<endl;

 

方法四:

我寫過一個宏,專門幹這個的!

#include "window.h"
#define BEGIN_RECORD\
{\
long ____temp_begin_time___;\
____temp_begin_time___=::GetTickCount();
#define END_RECORD(dtime)\
dtime=::GetTickCount()-____temp_begin_time___;\
}

用法:
    long tim;
    BEGIN_RECORD
    被測函數;
    END_RECORD(tim);//tim就是所求的時間差!

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.