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

标签 linux getrusage

这个 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/

相关文章:

linux - 查找并替换某个目录下所有文件和文件夹中的字符串

linux - 从 cron 运行命令无法正常工作

c++ - 在我的 linux 中调用了哪个版本的 close(),来自 posix lib 还是内核?

c++ - 基准代码——是否除以迭代次数?

c++ - Linux getrusage() maxrss 最大驻留集大小不随分配增加 (C++)

c++ - getrusage() 获取系统时间、用户时间。 Unix编程帮助

linux - 如何将图像转换为低宽度 200

c - 如何处理共享虚拟内存(Linux)

c - printf 如何影响 getrusage 在 C 中测量时间