简体   繁体   中英

Measure the time of a child process

I want to measure the time of a child process

#include <time.h>

int main() {
    ...
    time t begin, end, diff;
    ...
    //fork etc in here
    time(&begin);
    ...
    //some things
    ...
    time(&end);
    return 0;
}

I have 2 Time stamps now, is there a way to format it to the run-time of the child process to hours:minutes:seconds?

I have tried

diff = end - begin;

But I get a huge number then.

(Sorry for only a part of the code but it's on another PC.)

You should probably compute the difference using difftime instead of subtraction, in case your system uses some other format for time_t besides "integer number of seconds".

difftime returns the number of seconds between the two times, as a double . It's then a simple matter of arithmetic to convert to hours, minutes and seconds.

You can compute the difference with difftime :

double diff_in_seconds = difftime(end, begin);

or, for better precision, use one of C++11 chrono monotonic clocks such as std::steady_clock :

auto start = std::chrono::steady_clock::now();
// some things
auto end = std::chrono::steady_clock::now();
double time_in_seconds = std::chrono::duration_cast<double>(end - start).count();

See also this answer for details why you should use a monotonic clock.

The attempt in the question is a C way, not C++. In C++11 (assuming you have one), you can get 2 time points and then cast the difference between them to the units you need, as in the example here: http://en.cppreference.com/w/cpp/chrono/duration/duration_cast

Nearly copying the code:

auto t1 = std::chrono::high_resolution_clock::now();
// Call your child process here
auto t2 = std::chrono::high_resolution_clock::now();
std::cout << "Child process took "
          << std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count()
          << " milliseconds\n";

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