Saturday, September 6, 2014

Unix Prog: Time and Date(1)

1. time, gettimeofday

time system is used to return the number of seconds that has passed since the Epoch: 00:00:00 Jan 1st, 1970

Definition:
 ubuntu@ip-172-31-23-227:~$ less /usr/include/time.h  
 ......  
 /* Return the current time and put it in *TIMER if TIMER is not NULL. */  
 extern time_t time (time_t *__timer) __THROW;  
 ......  

gettimeofday can return the number of seconds and million seconds that has passed since the Epoch: 00:00:00 Jan 1st, 1970

Definition:
 ubuntu@ip-172-31-23-227:~$ less /usr/include/linux/time.h  
 ......  
 struct timeval {  
     __kernel_time_t     tv_sec;     /* seconds */  
     __kernel_suseconds_t  tv_usec;    /* microseconds */  
 };  
 ......  
 ubuntu@ip-172-31-23-227:~$ less /usr/include/x86_64-linux-gnu/sys/time.h  
 ......  
 /* Get the current time of day and timezone information,  
   putting it into *TV and *TZ. If TZ is NULL, *TZ is not filled.  
   Returns 0 on success, -1 on errors.  
   NOTE: This form of timezone information is obsolete.  
   Use the functions and variables declared in <time.h> instead. */  
 extern int gettimeofday (struct timeval *__restrict __tv,  
              __timezone_ptr_t __tz) __THROW __nonnull ((1));  
 ......  

Example_1, fileio.c:
 #include<stdio.h>  
 #include<stdlib.h>  
 #include<time.h>  
   
 int main(int argc, char* argv[])  
 {  
  time_t tt1, tt2;  
  if((tt1 = time(&tt2)) < 0) {  
   printf("time error!\n");  
   exit(1);  
  }  
   
  printf("%ld, %ld\n", tt1, tt2);  
  exit(0);  
 }  

shell:
Run the program, time function will return the number of seconds, also, if the argument address is not NULL, it will also populate the number of seconds there.
So tt1, tt2 should have same value.
 ubuntu@ip-172-31-23-227:~$ ./io.out  
 1410029633, 1410029633  

Example_2, fileio.c:
 #include<stdio.h>  
 #include<stdlib.h>  
 #include<time.h>  
   
 int main(int argc, char* argv[])  
 {  
  struct timeval tp;  
  if(gettimeofday(&tp, NULL) != 0) {  
   printf("gettimeofday error!\n");  
   exit(1);  
  }  
   
  printf("%ld, %ld\n", tp.tv_sec, tp.tv_usec);  
  exit(0);  
 }  

shell:
Run the program to return the number of seconds and the number of million seconds that has passed since Epoch 00:00:00 Jan 1st 1970.
 ubuntu@ip-172-31-23-227:~$ ./io.out  
 1410029890, 9741  

No comments:

Post a Comment