0

I am having a hard time adding two long ints, essentially what I want is the 'total' time it took using these two variables and I keep on getting 0.

struct rusage rusage;
getrusage(RUSAGE_SELF, &rusage); 
printf("TOTAL TIME \n");
printf("%ld.%06ld", (rusage.ru_utime.tv_sec, rusage.ru_utime.tv_usec), 
                    (rusage.ru_stime.tv_sec, rusage.ru_stime.tv_usec));

It prints out a 0. I am able to print out the the user time, system time, but I can't add them. Please help.

What the author wants isn't to add just two long integers, but to add two timeval structures' seconds and microseconds respectively.

4

5 回答 5

1

像这样的东西,但这可以写得更好:

  struct rusage rusage;
  struct rusage tusage;
  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);
于 2013-03-14T06:52:14.490 回答
0

您的代码既不显示结构也不显示填充方式。但是 printf 参数列表将两次 tv_usec 成员传递给函数。您使用逗号运算符并使用括号中最右边的成员 (tv_usec)。

于 2013-03-14T06:48:27.350 回答
0

您可以执行以下操作:

#include <sys/time.h>
struct timeval  StartTime, EndTime;
gettimeofday(&StartTime, NULL);
/...

// Your program

.../
gettimeofday(&EndTime, NULL);

printf ("Total time = %f seconds\n",
         (double) (tv2.tv_usec - tv1.tv_usec)/1000000 +
         (double) (tv2.tv_sec - tv1.tv_sec));
于 2013-03-14T06:53:32.860 回答
0

也许我不明白这一点,请尝试以下操作:

#include <stdio.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <stdlib.h>
int main(){
int i=0;
struct rusage rusage;
for(i=0;i<10000000;i++)
{
        free(malloc(4096));
}
getrusage(RUSAGE_SELF, &rusage);
printf("TOTAL TIME \n");
printf("%ld.%06ld\n",rusage.ru_utime.tv_sec, rusage.ru_utime.tv_usec);
printf("%ld.%06ld\n",rusage.ru_stime.tv_sec, rusage.ru_stime.tv_usec);
printf("%ld.%06ld\n",rusage.ru_stime.tv_sec+rusage.ru_utime.tv_sec, rusage.ru_stime.tv_usec+rusage.ru_utime.tv_usec);
}
于 2013-03-14T07:00:27.553 回答
0

我也不懂你的意思。也许是

double total_time = (rusage.ru_utime.tv_sec + rusage.ru_stime.tv_sec) / 1000.0
  + (rusage.ru_utime.tv_usec + rusage.ru_stime_tv_usec) * 1000

total_time 的单位是 ms。

于 2013-03-14T07:06:08.873 回答