[TIP] 소스 코드 시간 측정 코드

 

알고리즘 시험 대비 중 소스 코드 시간 측정이 필요할 때가 있다.

채점 사이트가 아닌 자체적으로 코드 성능을 확인하고 싶을 때

아래와 같이 chrono 라이브러리를 사용하여 측정해 보면 된다.

C++11 에서 추가된 라이브러리로 시간 측정시 용이하게 사용된다.

나노밀리 초까지 측정할 수 있다고 한다.


시작 시간과 종료 시간을 저장하고 그 차이를 출력하여 확인한다.

알고리즘 시험 시 대부분 채점은 수초 안에 끝나기 때문에 Milli sec 정도 측정하면 적당할 것 같다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <chrono>
using namespace std;
using namespace chrono;
 
void Loop()
{
    int x;
    for (int i = 1; i <= 50000; i++)
    {
        for (int j = 1; j <= 50000; j++)
        {
            x = (i * j)  + (i / j);
        }
    }
}
int main()
{
    system_clock::time_point start = system_clock::now();    // 시작 시간 
 
    Loop();
 
    system_clock::time_point end = system_clock::now();    // 종료 시간
 
    microseconds microSec = duration_cast<microseconds>(end - start);
    milliseconds milliSec = duration_cast<milliseconds>(end - start);
 
    cout << microSec.count() << "us" << endl;    // Mirco Sec
    cout << milliSec.count() <<"ms"<< endl;        // Milli Sec
}
cs



 

이 글을 공유하기

댓글

Designed by JB FACTORY