用C ++测量std :: system的实际执行时间

时间:2017-07-02 15:45:15

标签: c++ performance time stl

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

或者函数可能会立即返回而且不可能,在这种情况下还有其他方法来衡量分叉程序的执行吗?

感谢您的帮助。

3 个答案:

答案 0 :(得分:3)

除非您正在查看既不是具有类似sh的shell也不是Windows的POSIX的系统,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 ++没有标准的跨平台方式向您提供。

答案 1 :(得分: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;
 }

答案 2 :(得分:1)

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

但是让我们把重点放在Linux 上(至少在其他类似POSIX的系统上)。然后,您可以使用较低级别的系统调用fork(2)execve(2)wait4(2)并使用struct rusage(请参阅getrusage(2)获取详细信息) {1}}调用,特别是获取CPU时间。如果您只想要经过的真实时间,请使用<chrono> C++ facilities(或time(7)等较低级clock_gettime(2)内容...)

请注意,clock标准C函数提供了有关处理器时间的信息(在当前 process中),因此无法衡量分叉子进程(由wait4)将消耗。

相关问题