我想衡量子进程的时间
#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上。)
答案 0 :(得分:1)
如果您的系统除了“整数秒数”之外还使用difftime
的其他格式,您应该使用time_t
而不是减法来计算差异。
difftime
返回两次之间的秒数,为double
。然后,转换为小时,分钟和秒钟就算是一个简单的算术问题。
答案 1 :(得分:1)
您可以使用difftime
计算差异:
double diff_in_seconds = difftime(end, begin);
或者,为了更好的精度,使用C ++ 11 chrono单调时钟之一,例如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();
另请参阅this answer,了解有关使用单调时钟的详细信息。
答案 2 :(得分:1)
问题的尝试是C方式,而不是C ++。在C ++ 11中(假设您有一个),您可以获得2个时间点,然后将它们之间的差异转换为您需要的单位,如下例所示:http://en.cppreference.com/w/cpp/chrono/duration/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";