获取的getrusage()来衡量空调系统时间 [英] Getting getrusage() to measure system time in C

查看:265
本文介绍了获取的getrusage()来衡量空调系统时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想测量它需要执行一些code中的系统时间。要做到这一点,我知道我会说三明治两个电话之间code到的getrusage(),但我得到了一些意想不到的结果...

I would like to measure the system time it takes to execute some code. To do this I know I would sandwich said code between two calls to getrusage(), but I get some unexpected results...

#include <sys/time.h>
#include <sys/resource.h>
#include <unistd.h>
#include <stdio.h>

int main() {
  struct rusage usage;
  struct timeval start, end;
  int i, j, k = 0;

  getrusage(RUSAGE_SELF, &usage);
  start = usage.ru_stime;
  for (i = 0; i < 10000; i++) {
    /* Double loop for more interesting results. */
    for (j = 0; j < 10000; j++) {
      k += 20; 
    }
  }
  getrusage(RUSAGE_SELF, &usage);
  end = usage.ru_stime;

  printf("Started at: %ld.%lds\n", start.tv_sec, start.tv_usec);
  printf("Ended at: %ld.%lds\n", end.tv_sec, end.tv_usec);
  return 0;
}

我希望这会产生两个不同的数字,但很可惜!看到我的电脑想了两秒钟后,这是结果:

I would hope that this produces two different numbers, but alas! After seeing my computer think for a second or two, this is the result:

Started at: 0.1999s
Ended at: 0.1999s

难道我没有使用的getrusage()吧?为什么不应该这两个数字是不同的?如果我是根本错误的,有另一种方式来使用的getrusage()来衡量某些源$ C ​​$ C的系统时间?感谢您的阅读。

Am I not using getrusage() right? Why shouldn't these two numbers be different? If I am fundamentally wrong, is there another way to use getrusage() to measure the system time of some source code? Thank you for reading.

推荐答案

你误会用户和系统的时间之间的区别。你的榜样code是用户模式,主要执行(即运行应用程序code),而你测量,但系统的时间是在内核模式下执行花时间的一个量度(即处理系统呼叫)。

You're misunderstanding the difference between "user" and "system" time. Your example code is executing primarily in user-mode (ie, running your application code) while you are measuring, but "system" time is a measure of time spent executing in kernel-mode (ie, processing system calls).

ru_stime 是衡量系统时间正确的字段。你的测试程序只是碰巧不累积你检查这两个点之间的任何这样的时间。

ru_stime is the correct field to measure system time. Your test application just happens not to accrue any such time between the two points you check.

这篇关于获取的getrusage()来衡量空调系统时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆