如何在C ++中计算代码段的执行时间?
我们可以使用以下语法来计算代码片段的执行时间:
auto start = high_resolution_clock::now(); // Start time //代码段 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);
热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短