Introduction to the linux c time function time difftime

Header file: #include <time.h>

Define function: time_t time(time_t *t);

Function description: This function will return the number of seconds that have passed since UTC time on January 1, 1970 AD from 0:00:00 to the present. If t is not a null pointer, this function will also store the return value in the memory pointed to by the t pointer.

Return value: The number of seconds is returned for success, and the value of ((time_t)-1) is returned for failure. The reason for the error is stored in errno.

 

Header file: #include <time.h>

Define function: double difftime(time_t time2, time_t time1);

Function description: Returns the time interval between two time_t variables, that is, calculates the time difference between two moments.
 

Examples:

#include <time.h>
#include <stdio.h>
main()
{
   time_t t1=time(NULL);
   printf("t1 is : %d\n",t1);
   sleep(10);
   time_t t2=time(NULL);
   printf("t2 is : %d\n",t2);
   float tinterval=difftime(t2,t1);
   printf("the time interval is: %lf\n",tinterval);
}

Results of the:

[root@localhost charliye]# ./time
t1 is : 1456194488
t2 is : 1456194498
the time interval is: 10.000000

note:

1. The type of t1 and t2 should be time_t

2. When printf, the type of t1 and t2 should be %d, and the type of tinterval should be %lf

3. The return value unit of time is seconds, and the return value unit of difftime is also seconds.

4. The unit of sleep() is milliseconds under Windows, and the unit is seconds under Linux
 

 

Guess you like

Origin blog.csdn.net/whatday/article/details/114256877