精确计算代码执行时间

有的时候需要想知道一个函数执行消耗的时间,修改算法,或者优化带来的性能提升,一个高精度计时代码就需要了,而且要尽可能的高精度。

方法一:GetTickCount()

DWORD start = GetTickCount();

executeSmth();

printf("Elapsed: %i ms", GetTickCount() - start);

缺点显而易见,精度不够

方法二: QueryPerformanceCounter, QueryPerformanceFreQuency

LARGE_INTEGER StartingTime, EndingTime, ElapsedMicroseconds;

LARGE_INTEGER Frequency;

QueryPerformanceFrequency(&Frequency);

QueryPerformanceCounter(&StartingTime);

// Activity to be timed

QueryPerformanceCounter(&EndingTime);

ElapsedMicroseconds.QuadPart = EndingTime.QuadPart - StartingTime.QuadPart;

//

// We now have the elapsed number of ticks, along with the

// number of ticks-per-second. We use these values

// to convert to the number of elapsed microseconds.

// To guard against loss-of-precision, we convert

// to microseconds *before* dividing by ticks-per-second.

//

ElapsedMicroseconds.QuadPart *= 1000000;

ElapsedMicroseconds.QuadPart /= Frequency.QuadPart;

需要自己格式化显示,不方便


方法三:王者归来C++11

using namespace std;

using namespace std::chrono;

class NTime

{

public:

NTime() {

m_start = high_resolution_clock::now();

}

~NTime() {

m_end = high_resolution_clock::now();

double dif = duration_cast(m_end - m_start).count();

double dif_us = duration_cast(m_end - m_start).count();

double dif_ms = duration_cast(m_end - m_start).count();

printf("Elasped time is %lf ns. ", dif);

printf("Elasped time is %lf μs. ", dif_us);

printf("Elasped time is %lf ms. ", dif_ms);

}

private:

high_resolution_clock::time_point m_start, m_end;

};

boost的chrone已经在C++11标准库啦

测试代码,来个100次的for循环

int main()

{

{

NTime obj;

for (int i = 0; i < 100; i++)

;

}

return 0;

}

分别在relase 模式下,各个优化级别的情况

Optimizations (Favor Speed) (/Ox)

Elasped time is 600.000000 ns.

Elasped time is 0.000000 μs.

Elasped time is 0.000000 ms.


Disabled (/Od)

Elasped time is 600.000000 ns.

Elasped time is 0.000000 μs.

Elasped time is 0.000000 ms.

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章