以C++为单位测量程序的 CPU 时间和挂钟时间
Measure CPU time and wall clock time of a program in C++
std::clock()
测量程序持续时间内的时钟周期数。在下面的代码中,它是计算 CPU 时间还是挂钟时间?
标准::clock_t开始; 双倍持续时间;
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
时间可能比挂钟更快或更慢,具体取决于操作系统提供给程序的执行资源。
在这种情况下,您还可以编写一个简单的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,以便对某些内容进行计时。
相关文章:
- C++为构建时间获取QDateTime的可靠方法
- 从持续时间构造std::chrono::system_clock::time_point
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- while循环中while循环的时间复杂度是多少
- 使用简单类型列表实现的指数编译时间.为什么
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- 时间持续时间到时间字符串
- 使用时间,时间应该如何存储为变量?
- 将带有参考时间的时间戳转换为格式化时间
- 即使在多任务处理时,添加用户时间 + 系统时间(来自 shell 的时间命令)是否是一种可靠的措施?
- 为什么这个经过的时间(帧时间)计算会锁定我的游戏
- 如何使课程持续时间存储时间长度
- 如何格式化标准::时间持续时间
- 不取决于系统时间的时间
- C程序的示例长时间执行时间
- 当(执行时间)>>>(编译时间)时,多个编译单元是否仍然值得?
- 在时间::持续时间类型之间转换,其中两个分母的LCM都很大
- 获取评测函数持续时间的时间(以毫秒为单位)
- 将迭代器返回到多映射中最接近指定时间的时间
- 如何将毫秒添加到自epoch以来的时间持续时间