是否可以测量std::system(...)
的执行时间?在C++中测量std :: system的实际执行时间
或者,也许函数立即返回,这是不可能的,在这种情况下是否有任何其他方式来衡量分叉程序的执行?
感谢您的任何帮助。
是否可以测量std::system(...)
的执行时间?在C++中测量std :: system的实际执行时间
或者,也许函数立即返回,这是不可能的,在这种情况下是否有任何其他方式来衡量分叉程序的执行?
感谢您的任何帮助。
除非你正在寻找一个系统既不是POSIX与SH-像贝壳也不支持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'执行得太快。所以,现在我可以测量到底多快:) – CpCd0y
它是特定于实现的(因为AFAIU,C++标准没有详细说明std::system
使用的命令处理器;该命令处理器可能甚至不运行任何外部进程)。
但让我们关注Linux(或至少在其他POSIX系统)上的。然后,您可以使用较低级别的系统调用fork(2),execve(2),wait4(2)并使用struct rusage
(请参阅getrusage(2)以获取详细信息)填充该成功的wait4
调用,特别是获取CPU时间。如果你只想经过真正时间,使用<chrono>
C++ facilities(或下级time(7)的东西,如clock_gettime(2) ...)
注意,clock标准C函数提供了有关处理器时间(在电流process)所以不会测量分叉子进程(由std::system
)会消耗什么。
试试这个代码(对于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)](http://man7.org/linux/man-pages/man3/clock.3.html)...-给出了当前进程的近似值CPU时间(不包括子进程)。 Windows被称为是有缺陷的,因为它的“时钟”给出了 - 正确 - 实际使用时间的粗略近似值 –
顺便说一句,你的代码是C,并且OP询问关于C++ –
即使答案错误的版本 –
'系统'是关于执行一个命令。假设它是linux,因为你使用了'fork'。 'system(“time”YOUR_COMMAND)'就足够了,尽管时间消耗被打印到终端。 – Thiner
如果你想象测量其他子程序一样测量系统调用时间,你可以转到'rdtsc' /'gettimeofday'/...(time.h中的'time'是不推荐的,因为它只能返回当前秒,并没有用) – Thiner