简体   繁体   English

测量子进程的时间

[英]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? 我现在有2个时间戳,有没有办法将其格式化为子进程的运行时,以小时:分钟:秒?

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.) (对不起,仅部分代码,但它在另一台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". 如果系统对“ time_t ”使用除“整数秒数”之外的其他格式,则可能应该使用difftime而不是减法来计算差异。

difftime returns the number of seconds between the two times, as a double . difftime返回的两个时间之间的秒数,作为double It's then a simple matter of arithmetic to convert to hours, minutes and seconds. 然后,将其转换为小时,分钟和秒是一个简单的算术问题。

You can compute the difference with difftime : 您可以使用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 : 或者,为了获得更高的精度,请使用C ++ 11 计时单调时钟之一,例如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++. 问题中的尝试是C方式,而不是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 在C ++ 11中(假设您有一个),您可以获得2个时间点,然后将它们之间的差值转换为所需的单位,如此处的示例所示: http : //en.cppreference.com/w/cpp /计时/持续时间/ 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";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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