我们可以通过使用 时态 在C++ 11中引入了库。我们已经在 如何用C语言测量程序所用的时间 上面描述的函数也在C++中支持,但它们是C特定的。对于干净和健壮的C++程序,我们应该力求只用C++特定的语言构造。 时态 有两个截然不同的对象——时间点和持续时间。顾名思义,时间点代表一个时间点,而持续时间代表一个时间间隔或跨度。C++库允许我们减去两个时间点,以获得在时间间隔内传递的时间间隔。使用提供的方法,我们还可以将此持续时间转换为适当的单位。 这个 时态 为我们提供三个不同精度的时钟。这个 高分辨率时钟 是最准确的,因此用于测量执行时间。 步骤1:在调用函数之前获取时间点
null
CPP
#include <chrono> using namespace std::chrono; // Use auto keyword to avoid typing long // type definitions to get the timepoint // at this instant use function now() auto start = high_resolution_clock::now(); |
第2步:调用函数后获取时间点
CPP
#include <chrono> using namespace std::chrono; // After function call auto stop = high_resolution_clock::now(); |
第3步:获得时间点的差异,并将其转换为所需的单位
CPP
// 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; |
下面给出一个完整的C++程序演示程序。我们用一些随机数填充一个向量,并测量sort()函数对该向量进行排序所需的时间。
CPP
// C++ program to find out execution time of // of functions #include <algorithm> #include <chrono> #include <iostream> #include<vector> using namespace std; using namespace std::chrono; // For demonstration purpose, we will fill up // a vector with random integers and then sort // them using sort function. We fill record // and print the time required by sort function int main() { vector< int > values(10000); // Generate Random values auto f = []() -> int { return rand () % 10000; }; // Fill up the vector generate(values.begin(), values.end(), f); // Get starting timepoint auto start = high_resolution_clock::now(); // Call the function, here sort() sort(values.begin(), values.end()); // Get ending timepoint auto stop = high_resolution_clock::now(); // Get duration. Substart timepoints to // get duration. To cast it to proper unit // use duration cast method auto duration = duration_cast<microseconds>(stop - start); cout << "Time taken by function: " << duration.count() << " microseconds" << endl; return 0; } |
输出:(取决于机器)
Time taken by function: 3062 microseconds
工具书类 https://www.geeksforgeeks.org/chrono-in-c/
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END