LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Negative System time with RUsage (https://www.linuxquestions.org/questions/programming-9/negative-system-time-with-rusage-233885/)

Isserex 09-22-2004 12:25 PM

Negative System time with RUsage
 
I have a question and I am unsure if it fits this category since it may be a technical question of either Linux or the exact Distribute but I will ask anyhow:

I am attempting to create a program to measure time for an internal C function call using getrusage. However often the difference between the system time is negative (where the initial system time is larger then the final system time). I was wondering if that is actuate or if I having having problems with my program. I know that time can not go backwards on a computer.


Here is the exact code:
main () {
struct rusage start, end;
double systemtime, usertime;
int i, j;

for (i = 0; i < 10; i++) {

usertime = 0.0;
systemtime = 0.0;

getrusage(RUSAGE_SELF, &start);

for (j = 0; j < 100000000;j++) { printf(""); }


getrusage(RUSAGE_SELF, &end);

usertime = end.ru_utime.tv_sec+end.ru_utime.tv_usec*1e-6 -
(start.ru_utime.tv_sec+start.ru_utime.tv_usec*1e-6);

systemtime = end.ru_stime.tv_sec+end.ru_stime.tv_usec*1e-6 -
(start.ru_stime.tv_sec+start.ru_stime.tv_usec*1e-6);

printf("%f\n", systemtime);
printf("%f\n", usertime);
}
}

itsme86 09-22-2004 12:52 PM

It works perfectly fine for me. Here's the cleaned-up code I used, but it's essentially the same as yours:
Code:

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

int main(void)
{
  struct rusage start, end;
  double systemtime, usertime;
  int i, j;

  for (i = 0;i < 10;i++)
  {
    usertime = 0.0;
    systemtime = 0.0;

    if(getrusage(RUSAGE_SELF, &start) == -1)
    {
      puts("Error!");
      return 1;
    }

    for(j = 0;j < 100000000;j++);  // Whole loop

    if(getrusage(RUSAGE_SELF, &end) == -1)
    {
      puts("Error!");
      return 1;
    }

    usertime = end.ru_utime.tv_sec+end.ru_utime.tv_usec*1e-6 -
              (start.ru_utime.tv_sec+start.ru_utime.tv_usec*1e-6);

    systemtime = end.ru_stime.tv_sec+end.ru_stime.tv_usec*1e-6 -
                (start.ru_stime.tv_sec+start.ru_stime.tv_usec*1e-6);

    printf("%f\n", systemtime);
    printf("%f\n", usertime);
  }

  return 0;
}

And my results:
Quote:

itsme@dreams:~/C$ ./rusage
0.000000
1.020000
0.000000
1.000000
0.000000
1.020000
0.000000
1.010000
0.000000
1.020000
0.000000
1.010000
0.000000
1.010000
0.000000
1.010000
0.000000
1.010000
0.000000
1.000000
itsme@dreams:~/C$

Isserex 09-22-2004 06:42 PM

Actually it works fine for short programs and that is why I needed the print statement. If you include the print statement, the process will take longer and that is when the negative numbers show up (like 2 out of 10 times).


All times are GMT -5. The time now is 02:35 PM.