เราสามารถคำนวณเวลาดำเนินการของข้อมูลโค้ดโดยใช้รูปแบบต่อไปนี้ −
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() เราบันทึกเวลาที่ใช้โดยฟังก์ชัน sum() โดยใช้ฟังก์ชันที่กำหนดไว้ล่วงหน้าและคลาส “chrono”
auto start = high_resolution_clock::now(); sum(28, 8); auto stop = high_resolution_clock::now(); auto duration = duration_cast<microseconds>(stop - start);