[英]Measure CPU time and wall clock time of a program in C++
std::clock()
measures the number of clock ticks within the duration of your program. std::clock()
测量程序持续时间内的时钟周期数。 In the following code, does it calculate the CPU time or wall clock time? 在以下代码中,它是否计算CPU时间或挂钟时间?
std::clock_t start; std :: clock_t start; double duration;
双倍期;
start = std::clock();
/* Your algorithm here */
duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;
In another scenario, with the following code: 在另一种情况下,使用以下代码:
std::clock_t start;
double time;
start = std::clock();
time = start / (double) CLOCKS_PER_SEC;
What will the value of time be? 时间的价值是多少?
From the documentation : 从文档 :
std::clock
time may advance faster or slower than the wall clock, depending on the execution resources given to the program by the operating system.std::clock
time可能比挂钟更快或更慢,具体取决于操作系统给程序执行的资源。
In this case you can also write a simple lambda (especially simple in C++14) that measures the time taken by any callable object, like this: 在这种情况下,您还可以编写一个简单的lambda(在C ++ 14中特别简单),它可以测量任何可调用对象所用的时间,如下所示:
#include <iostream>
#include <chrono>
auto timing = [](auto&& F, auto&&... params) // need C++14 for auto lambda parameters
{
auto start = std::chrono::steady_clock::now();
F(std::forward<decltype(params)>(params)...); // execute the function
return std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - start).count();
};
void f(std::size_t numsteps) // we'll measure how long this function runs
{
volatile std::size_t i{}; // need volatile, otherwise the compiler optimizes the loop
for(i = 0; i < numsteps; ++i);
}
int main()
{
auto taken = timing(f, 500'000'000); // measure the time taken to run f()
std::cout << "Took " << taken << " milliseconds" << std::endl;
taken = timing(f, 100'000'000); // measure again
std::cout << "Took " << taken << " milliseconds" << std::endl;
}
You can then reuse the lambda whenever you want to time something. 然后,您可以在需要时间时重复使用lambda。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.