gpt4 book ai didi

linux - 为什么使用 getrusage() 测量的已用用户时间不接近完全一致?

转载 作者:太空宇宙 更新时间:2023-11-04 12:40:03 24 4
gpt4 key购买 nike

这个 C++ 程序给出了可变的结果。有时变化很大。我调用 getrusage() 一次以获得开始时间。然后我循环调用 rand() 500000000 次。然后我再次调用 getrusage() 并输出两次 getrusage() 调用之间经过的用户和系统时间。根据它包含的内容,我可以理解为什么“系统时间”不一致。但我希望“用户时间”是(主进程)线程处于运行状态的时间。我认为从一次运行到下一次运行将非常接近完全一致。但事实并非如此。

#include <iostream>
#include <exception>
#include <cstdlib>

#include <sys/types.h>
#include <sys/time.h>
#include <sys/resource.h>

using std::cout;

// tm is end time on intput, time different from start to end on output.
void since(const struct timeval start, struct timeval &tm)
{
if (tm.tv_sec == start.tv_sec)
{
tm.tv_sec = 0;
tm.tv_usec -= start.tv_usec;
}
else
{
tm.tv_usec += 1000000 - start.tv_usec;
tm.tv_sec -= start.tv_sec;
if (tm.tv_usec >= 1000000)
{
tm.tv_usec -= 1000000;
++tm.tv_sec;
}
}
}

void out_tm(const struct timeval &tm)
{
cout << "seconds: " << tm.tv_sec;
cout << " useconds: " << tm.tv_usec;
}

void bail(const char *msg)
{
cout << msg << '\n';
std::terminate();
}

int main()
{
struct rusage usage;

if (getrusage(RUSAGE_SELF, &usage))
bail("FAIL: getrusage() call failed");

struct timeval user_tm = usage.ru_utime;
struct timeval sys_tm = usage.ru_stime;

for (unsigned i = 0; i < 500000000; ++i)
std::rand();

if (getrusage(RUSAGE_SELF, &usage))
bail("FAIL: getrusage() call failed");

since(user_tm, usage.ru_utime);
user_tm = usage.ru_utime;

since(sys_tm, usage.ru_stime);
sys_tm = usage.ru_stime;

cout << "User time: ";
out_tm(user_tm);

cout << "\nSystem time: ";
out_tm(sys_tm);
cout << '\n';

return(0);
}

最佳答案

gnu推荐以下用于测量时差的代码。

与您的代码有一些差异可能会导致时间跳跃,请尝试一下。

int
timeval_subtract (struct timeval *result, struct timeval *x, struct timeval *y)
{
/* Perform the carry for the later subtraction by updating y. */
if (x->tv_usec < y->tv_usec) {
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000) {
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}

/* Compute the time remaining to wait.
tv_usec is certainly positive. */
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;

/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
}

关于linux - 为什么使用 getrusage() 测量的已用用户时间不接近完全一致?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40534209/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com