Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

C++에서 코드 조각의 실행 시간을 계산하는 방법은 무엇입니까?

<시간/>

다음 구문을 사용하여 코드 조각의 실행 시간을 계산할 수 있습니다. -

auto start = high_resolution_clock::now(); // Start time
// Code snippet
auto stop = high_resolution_clock::now(); // Stop time
auto duration = duration_cast<microseconds>(stop - start); // Duration

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);