龙空技术网

精确计算代码执行时间

大头兵 659

前言:

此刻你们对“执行一次for循环的时间怎么算出来”大约比较注意,大家都需要剖析一些“执行一次for循环的时间怎么算出来”的相关文章。那么小编也在网摘上收集了一些有关“执行一次for循环的时间怎么算出来””的相关内容,希望同学们能喜欢,我们快快来学习一下吧!

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

方法一: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<nanoseconds>(m_end - m_start).count();

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

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

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

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

printf("Elasped time is %lf ms.\n", 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.

标签: #执行一次for循环的时间怎么算出来