简体   繁体   中英

adding two long ints in C

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.

Something like this, but this can be written better:

  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);

Your code doesn't show neither the structure nor how it is filled. But the printf arguments list passes two times the tv_usec member to the function. You use the comma operator and the right-most member in parenthesis (tv_usec) is used.

You can do something like:

#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));

Maybe i do not get the point, please try the bellow:

#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);
}

i can't get your point too. maybe it is

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

the total_time's unit is ms.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM