在 C++ 测量函数的执行时间
问题说明
我想了解某个函数在我的 C 程序中在 Linux 上执行所需的时间.之后,我想做一个速度比较.我看到了几个时间函数,但最终从 boost 得到了这个.时间:
I want to find out how much time a certain function takes in my C program to execute on Linux. Afterwards, I want to make a speed comparison . I saw several time function but ended up with this from boost. Chrono:
process_user_cpu_clock, captures user-CPU time spent by the current process
现在,我不清楚是否使用上述功能,我是否会获得 CPU 在该功能上花费的唯一时间?
Now, I am not clear if I use the above function, will I get the only time which CPU spent on that function?
其次,我找不到任何使用上述功能的示例.任何人都可以帮助我如何使用上述功能吗?
Secondly, I could not find any example of using the above function. Can any one please help me how to use the above function?
PS:现在,我正在使用 std::chrono::system_clock::now()
以秒为单位获取时间,但是由于每次 CPU 负载不同,这会给我不同的结果.
P.S: Right now , I am using std::chrono::system_clock::now()
to get time in seconds but this gives me different results due to different CPU load every time.
正确答案
它是 C 11 中非常易于使用的方法.您必须使用 标头中的 std::chrono::high_resolution_clock
.
It is a very easy-to-use method in C 11. You have to use std::chrono::high_resolution_clock
from <chrono>
header.
像这样使用它:
#include <chrono>
/* Only needed for the sake of this example. */
#include <iostream>
#include <thread>
void long_operation()
{
/* Simulating a long, heavy operation. */
using namespace std::chrono_literals;
std::this_thread::sleep_for(150ms);
}
int main()
{
using std::chrono::high_resolution_clock;
using std::chrono::duration_cast;
using std::chrono::duration;
using std::chrono::milliseconds;
auto t1 = high_resolution_clock::now();
long_operation();
auto t2 = high_resolution_clock::now();
/* Getting number of milliseconds as an integer. */
auto ms_int = duration_cast<milliseconds>(t2 - t1);
/* Getting number of milliseconds as a double. */
duration<double, std::milli> ms_double = t2 - t1;
std::cout << ms_int.count() << "ms
";
std::cout << ms_double.count() << "ms";
return 0;
}
这将测量函数long_operation
的持续时间.
This will measure the duration of the function long_operation
.
可能的输出:
150ms
150.068ms
工作示例:https://godbolt.org/z/oe5cMd
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tangicahg
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
希伯来语的空格句子标记化错误
it1352 06-22 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20