测量 std::系统的实际执行时间(以 C++ 为单位)

Measure std::system's real execution time in C++

本文关键字:C++ 为单位 执行时间 std 系统 测量      更新时间:2023-10-16

可以测量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(将消耗的内容。