C++ 코드 실행 시간

규규·2024년 3월 7일
0

C++

목록 보기
9/21

Wall time, CPU time

Wall time (clock time, wall-clock time)

  • 프로그램 실행 총 시간

CPU Time

  • CPU 가 프로그램 명령어를 실행 한 시간 (I/O 시간을 제외)

시간 측정 방법

<time.h> 및 clock()

  • 기본 ms 단위로 측정
  • 사용 예시
#include <iostream>
#include <ctime>
using namespace std;
 
int main() {
    clock_t start, finish;
    double duration;
 
    start = clock();
    
    /*실행 시간을 측정하고 싶은 코드*/
 
    finish = clock();
 
    cout << (double)(finish - start) << " ms" << endl;
 
    return 0;
}

chrono library

  • Wall time 을 측정하는 최선의 방법.
  • time 함수보다 다양한 기능을 제공하고 정밀도가 훨씬 높음.
  • high_resolution_clock 을 사용하는게 가장 정확성 높음.
  • 사용 예시
#include <chrono>
using namespace std::chrono;

auto start = high_resolution_clock::now();
target_function();
auto stop = high_resolution_clock::now();

// Subtract stop and start timepoints and
// cast it to required unit. Predefined units
// are nanoseconds, microseconds, milliseconds,
// seconds, minutes, hours. Use duration_cast()
// function.
auto duration = duration_cast<microseconds>(stop - start);
 
// To get the value of duration use the count()
// member function on the duration object
cout << duration.count() << endl;

time 명령어

  • UNIX 에서는 time 명령어를 통해서 실행 파일의 실행 시간을 측정 할 수 있음.

출처

profile
복습용 저장소

0개의 댓글