繁体   English   中英

测量子进程的时间

[英]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;
}

我现在有2个时间戳,有没有办法将其格式化为子进程的运行时,以小时:分钟:秒?

我努力了

diff = end - begin;

但是我得到了很多。

(对不起,仅部分代码,但它在另一台PC上。)

如果系统对“ time_t ”使用除“整数秒数”之外的其他格式,则可能应该使用difftime而不是减法来计算差异。

difftime返回的两个时间之间的秒数,作为double 然后,将其转换为小时,分钟和秒是一个简单的算术问题。

您可以使用difftime计算差异:

double diff_in_seconds = difftime(end, begin);

或者,为了获得更高的精度,请使用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();

另请参阅此答案以了解为什么您应该使用单调时钟的详细信息。

问题中的尝试是C方式,而不是C ++。 在C ++ 11中(假设您有一个),您可以获得2个时间点,然后将它们之间的差值转换为所需的单位,如此处的示例所示: http : //en.cppreference.com/w/cpp /计时/持续时间/ duration_cast

几乎复制代码:

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