简体   繁体   中英

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

Is it possible to measure std::system(...) 's execution time ?

Or maybe the function returns immediately and it's not possible, and in this case is there any other way to measure the execution of a forked program ?

Thanks for any help.

Unless you are looking at a system that is neither POSIX with a sh-like shell nor Windows, std::system is synchronous and returns the result of the command. You can use the standard high resolution timer to measure wall time:

#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";
}

If you're rather interested in the amount of CPU time that the process used, I don't think that C++ has a standard and cross-platform way of offering that to you.

Try this code (for 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;
 }

It is implementation specific (since, AFAIU, the C++ standard does not tell much about the command processor used by std::system ; that command processor might not even run any external processes).

But let's focus on Linux (or at least on other POSIX like systems). Then, you could use the lower level system calls fork(2) , execve(2) , wait4(2) and use the struct rusage (see getrusage(2) for details) filled by that successful wait4 call, notably to get the CPU time. If you want just the elapsed real time, use <chrono> C++ facilities (or lower-level time(7) things such as clock_gettime(2) ...)

Notice that the clock standard C function gives information about processor time (in the current process ) so won't measure what a forked child process (by std::system ) would consume.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM