【问题标题】:Measure std::system's real execution time in C++在 C++ 中测量 std::system 的实际执行时间
【发布时间】:2017-07-02 15:45:14
【问题描述】:

是否可以测量std::system(...)的执行时间?

或者函数可能立即返回并且不可能,在这种情况下,是否有任何其他方法可以测量分叉程序的执行?

感谢您的帮助。

【问题讨论】:

  • system 是关于执行命令。假设它是 linux,因为您使用了“fork”。 system("time " YOUR_COMMAND) 就够了,虽然耗时会打印到终端。
  • 如果你想像其他子程序一样测量system的调用时间,可以转向rdtsc/gettimeofday/...(time in time.h 不推荐,因为只能返回当前秒,没有用)

标签: c++ performance time stl


【解决方案1】:

除非您正在查看的系统既不是带有类似 sh 的 shell 的 POSIX 也不是 Windows,std::system 是同步的并返回命令的结果。你可以使用标准的high resolution timer来测量挂墙时间:

#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() << " microseconds\n";
}

如果您对进程使用的 CPU 时间量比较感兴趣,我认为 C++ 没有标准的跨平台方式来提供给您。

【讨论】:

  • 感谢您的回答。我的问题实际上是std::system 执行得太快了。所以,现在我可以准确地测量出有多快:)
【解决方案2】:

试试这个代码(适用于 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;
 }

【讨论】:

  • 行不通。在 POSIX 系统上 clock() -see clock(3)...- 给出当前进程 CPU 时间的近似值(不包括子进程)。众所周知,Windows 有缺陷,因为它的clock 错误地给出了实际经过时间的粗略近似
  • system() 是阻塞的,一直等到它返回,然后检查状态是否正常返回,然后才计算时间,你能告诉我什么问题吗? @BasileStarynkevitch
  • clock 测量当前进程的处理器时间(不包括子进程)
  • 我明白,但是 system() 是 BLOCKING,这意味着父级被挂起,直到系统返回,这就是为什么调用 clock() 来获取上一次调用之间的时间差。
  • 是的,你是对的!我已经编辑了我的代码以实现另一个逻辑@BasileStarynkevitch。谢谢指出!
【解决方案3】:

它是特定于实现的(因为,AFAIU,C++ 标准并没有详细说明 std::system 使用的命令处理器;该命令处理器甚至可能不运行任何外部进程)。

但让我们关注Linux(或至少关注其他类似POSIX 的系统)。然后,您可以使用较低级别的系统调用fork(2)execve(2)wait4(2) 并使用由成功的wait4 调用填充的struct rusage(有关详细信息,请参阅getrusage(2)),特别是获取CPU 时间.如果您只想要经过的真实时间,请使用&lt;chrono&gt; C++ facilities(或更低级别的time(7),例如clock_gettime(2)...)

请注意,clock 标准 C 函数提供了有关 处理器时间(在 当前process 中)的信息,因此不会测量分叉子进程( std::system) 会消耗。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-23
    • 1970-01-01
    • 2023-04-10
    • 2023-03-09
    • 2013-03-21
    • 2016-06-15
    相关资源
    最近更新 更多