[英]Measure CPU time and wall clock time of a program in C++
std::clock()
测量程序持续时间内的时钟周期数。 在以下代码中,它是否计算CPU时间或挂钟时间?
std :: clock_t start; 双倍期;
start = std::clock();
/* Your algorithm here */
duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;
在另一种情况下,使用以下代码:
std::clock_t start;
double time;
start = std::clock();
time = start / (double) CLOCKS_PER_SEC;
时间的价值是多少?
从文档 :
std::clock
time可能比挂钟更快或更慢,具体取决于操作系统给程序执行的资源。
在这种情况下,您还可以编写一个简单的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;
}
然后,您可以在需要时间时重复使用lambda。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.