Computer >> 컴퓨터 >  >> 프로그래밍 >> C++

C++에서 코드 실행 시간을 측정하는 방법 (chrono 라이브러리 활용)

C++에서 특정 코드 조각의 실행 시간을 측정해야 하는 경우가 자주 있습니다. 성능 최적화, 알고리즘 비교, 병목 지점 분석 등을 위해서는 정확한 시간 측정이 필수적입니다. 이 글에서는 C++11부터 표준으로 제공되는 chrono 라이브러리를 활용해 코드 실행 시간을 간단하게 측정하는 방법을 알아보겠습니다.

기본 문법

코드의 시작 지점과 종료 지점에서 시간을 기록하고, 그 차이를 계산하면 실행 시간을 구할 수 있습니다.

auto start = high_resolution_clock::now(); // 시작 시간 기록
// 측정할 코드 작성
auto stop = high_resolution_clock::now(); // 종료 시간 기록
auto duration = duration_cast<microseconds>(stop - start); // 경과 시간 계산

chrono 헤더 파일

high_resolution_clock 클래스는 <chrono> 헤더 파일에 정의되어 있습니다. now() 함수는 호출된 시점의 현재 시간을 나타내는 값을 반환합니다.

따라서 코드 실행 시간을 측정하려면 먼저 아래와 같이 헤더 파일을 포함해야 합니다.

#include <chrono>
using namespace std::chrono;

전체 예제 코드

다음은 두 수의 합을 계산하는 함수의 실행 시간을 측정하는 전체 예제입니다.

#include <iostream>
#include <chrono>
using namespace std::chrono;
using namespace std;
int sum(int x, int y) {
    int s = x + y;
    cout << "The sum of numbers : " << s;
}
int main() {
    auto start = high_resolution_clock::now();
    sum(28, 8);
    auto stop = high_resolution_clock::now();
    auto duration = duration_cast<microseconds>(stop - start);
    cout << "\nTime taken by function : "<< duration.count() << " microseconds";
    return 0;
}

실행 결과

The sum of numbers : 36
Time taken by function : 42 microseconds

코드 설명

위 프로그램에서는 두 수의 합을 계산하는 sum() 함수를 정의했습니다.

int sum(int x, int y) {
    int s = x + y;
    cout << "The sum of numbers : " << s;
}

main() 함수 내부에서는 chrono 라이브러리가 제공하는 클래스와 함수를 사용하여 sum() 함수의 실행 시간을 기록했습니다.

auto start = high_resolution_clock::now();
sum(28, 8);
auto stop = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(stop - start);

주요 구성 요소 정리

high_resolution_clock::now(): 시스템이 제공하는 가장 높은 해상도의 클럭으로, 호출 시점의 시간을 반환합니다.

duration_cast<microseconds>: 두 시점 사이의 시간 차이를 마이크로초(μs) 단위로 변환합니다. 필요에 따라 milliseconds, seconds 등 다른 단위로도 변환할 수 있습니다.

duration.count(): 변환된 시간 값을 숫자로 출력합니다.

마무리

이처럼 chrono 라이브러리를 활용하면 단 몇 줄의 코드로 특정 함수나 코드 블록의 실행 시간을 정밀하게 측정할 수 있습니다. 더 높은 정밀도가 필요하다면 nanoseconds 단위를, 가독성이 중요하다면 millisecondsseconds 단위를 사용하는 것이 좋습니다. 성능 분석이나 알고리즘 최적화 작업 시 이 방법을 적극적으로 활용해 보시기 바랍니다.