测量 std::系统的实际执行时间(以 C++ 为单位)
Measure std::system's real execution time in C++
可以测量std::system(...)
的执行时间吗?
或者也许函数会立即返回并且不可能,在这种情况下,还有其他方法可以测量分叉程序的执行吗?
感谢您的任何帮助。
除非你看到的系统既不是POSIX的shell,也不是Windows,否则std::system
是同步的,并返回命令的结果。您可以使用标准的高分辨率计时器来测量挂断时间:
#include <chrono>
#include <cstdlib>
#include <iostream>
int main()
{
auto before = std::chrono::high_resolution_clock::now();
std::system("sleep 3");
auto after = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(
after - before);
std::cout << "It took " << duration.count() << " microsecondsn";
}
如果您对进程使用的 CPU 时间量相当感兴趣,我认为C++没有标准和跨平台的方式来为您提供它。
试试这段代码(适用于 Linux 和 POSIX(,
#include<time.h>
#include<sys/types.h>
#include<sys/wait.h>
#include <iostream>
#include <cstdlib>
struct tms st_time;
struct tms ed_time;
int main()
{
times(&st_time);
std::system("your call");
times(&ed_time);
std::cout<<"Total child process time ="
<<((ed_time.tms_cutime - st_time.tms_cutime)
+(ed_time.tms_cstime - st_time.tms_cstime))/CLOCKS_PER_SEC;
}
它是特定于实现的(因为,AFAIU,C++标准并没有说明std::system
使用的命令处理器;该命令处理器甚至可能不运行任何外部进程(。
但是让我们关注Linux(或者至少在其他类似POSIX的系统(。然后,您可以使用较低级别的系统调用 fork(2(、execve(2(、wait4(2( 并使用由该成功wait4
调用填充的struct rusage
(有关详细信息,请参阅 getrusage(2(,特别是获取 CPU 时间。 如果您只想要经过的实时时间,请使用<chrono>
C++设施(或较低级别的时间(7((之类的东西,例如clock_gettime(2(...(
请注意,时钟标准 C 函数提供有关处理器时间(在当前进程中(的信息,因此不会测量分叉子进程(按std::system
(将消耗的内容。
相关文章:
- 以天C++为单位的两个时间戳之间的差异
- 如何以毫秒为单位获取开始时间和 now() 之间的毫秒差异(以 C++为单位?
- 从原始字节解码协议缓冲区(以 C++为单位)
- 如何在 c++ 中确定一条指令(以字节为单位)在哪里结束,另一条指令从哪里开始?
- 编写以 C++ 为单位返回值的函数
- 以C++为单位进行运行长度编码
- 如何找到两个日期之间的时间差异(以秒和纳秒为单位)?
- arr[n] 是否以 C++ 为单位打印数组的长度?
- 字符串数组上的 sizeof 运算符以 C++ 为单位给出不同的输出
- 以 C++ 为单位具有输出限制的排列
- 以 GDB 为单位指定浮点精度
- 整数数据如何以位为单位存储在内存中?不是右对齐吗?
- 如何在没有硬编码的情况下以C++为单位获取类数组的长度?
- 指针引用的生存期(以 C++为单位)
- 以字符为单位设置控制台大小
- 获取嵌套 stl 容器的大小(以字节为单位)
- 有没有一种 STL 方法可以找到字符串的所有排列,给出一个以 C++ 为单位的大小?
- 二进制数组中最大连续 1 的起始和结束索引,以 C++ 为单位
- 正向声明的枚举,默认值以.h为单位
- 常量"C"占用的空间(以字节为单位)