所以我用rusage打印出用户和系统处理命令所需的时间,大致如下,

           //DO STUFF HERE
           printf(" TOTAL TIMES: ");
           tusage.ru_utime.tv_sec  = rusage.ru_utime.tv_sec + rusage.ru_stime.tv_sec;

最佳答案

试试这个:

#include <stdio.h>
#include <sys/resource.h>
int main() {
  struct rusage rusage;
  struct rusage tusage;
  int i, j, r=0;
  for (i = 0; i < 10000; i++) {
    for (j = 1; j < 100000; j++) {
      r = i % j + i / j;
    }
  }
  getrusage(RUSAGE_SELF, &rusage);
  printf("TOTAL TIME \n");
  tusage.ru_utime.tv_sec =  rusage.ru_utime.tv_sec + rusage.ru_stime.tv_sec;
  tusage.ru_utime.tv_usec = rusage.ru_utime.tv_usec + rusage.ru_stime.tv_usec;
  tusage.ru_utime.tv_sec += tusage.ru_utime.tv_usec / 1000000;
  tusage.ru_utime.tv_usec = tusage.ru_utime.tv_usec % 1000000;
  printf("%ld.%06ld\n", tusage.ru_utime.tv_sec, tusage.ru_utime.tv_usec);

  return r;
}

10-01 21:30