简体   繁体   中英

Times return value 0 in Linux C

I begin learn about the Linux C,but i meet the problem so confused me.
I use the function times .but return the value equals 0.
ok i made the mistak,I changed the code: But the is not much relative with printf. clock_t is define with long in Linux.so i convert clock_t to long.
This is my code:

#include <sys/times.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
   long clock_times;
   struct tms begintime;
   sleep(5);
   if((clock_times=times(&begintime))==-1)
      perror("get times error");
   else
   {
      printf("%ld\n",(long)begintime.tms_utime);
      printf("%ld\n",(long)begintime.tms_stime);
      printf("%ld\n",(long)begintime.tms_cutime);
      printf("%ld\n",(long)begintime.tms_cstime);
   }
   return 0;
}

the output: 0 0 0 0
the also return 0;
and I using gdb to debug,Also the variable of begintimes also to be zero. there is no relative with printf function. Please

Your code using close to none CPU time, so results are correct. Sleep suspends your program execution - everything that happens in this time is not your execution time, so it wouldn't be counted.

Add empty loop and you'll see the difference. (ofc., disable compiler optimisations - or empty loop will be removed).

Take a look at 'time' program output (time ./a.out) - it prints 'real' time (estimated by gettimeofday(), i suppose), user time (time wasted by your userspace code) and system time (time wasted within system calls - eg write to file, open network connection, etc.).

(sure, by 'wasted' i mean 'used', but whatever)

This is not unusual; the process simply hasn't used enough CPU time to measure. The amount of time the process spends in sleep() doesn't count against the program's CPU time, as times() measures The CPU time charged for the execution of user instructions (among other related times) which is the amount of time the process has spent executing user/kernel code.

Change your program to the following which uses more CPU and can therefore be measured:

#include <sys/times.h>
#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
   long clock_times;
   struct tms begintime;
   unsigned i;

   for (i = 0; i < 1000000; i++)
      time(NULL);    // An arbitrary library call

   if((clock_times=times(&begintime))==-1)
      perror("get times error");
   else
   {
      printf("%ld %ld %ld %ld\n",
        (long)begintime.tms_utime,
        (long)begintime.tms_stime,
        (long)begintime.tms_cutime,
        (long)begintime.tms_cstime);
   }
   return 0;
}

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