cm06 Time
cm06 Time
I There are 2 main units for time (what time is it ? what date
is it ? and some ticks of a clock).
I The data-structure time_t can contain the current date and
time, the date and time of creation of a file, etc. It contains
the number of seconds since The Epoch. Epoch is January,
1st 1970 at 00:00:00 UTC (it used to be GMT before 1986).
Time is stored in UTC format (no time zone). time_t used
to be encoded using 32 bits (that would be an issue in 2038
(number of seconds ≥ 231 ). So it switched to 64 bits (from
Linux ≥ 3.17) A value of time time_t is easy to deal with by
the kernel, but not at all for the user.
Making it readable by a human
I How to convert a time_t structure into something readable ?
I It has to take into account the time zone, daylight saving,
dates of changes in daylight saving, years with 366 days,
additionnal seconds - e.g. 1 second was added to time after
23:59:59 at the end of December 31st, 2016.
I This can be achieved using some library functions localtime,
asctime,strftime. Indeed, it is not a concern of the kernel.
I clock_t This unit allows to compute the CPU time used by a
process for instance. It counts a nuber of ticks from the clock.
The unit depends on the configuration of the kernel. POSIX
provides a primitive long sysconf(int p) where p is a
parameter of configuration.
I E.g. freq = sysconf(_SC_CLK_TCK) returns the number of
tops of the clock in one second.
I It can be used to compute the CPU consumption of a process.
At each clock interruption, the kernel increases a counter of
the current process (+1). It provides an estimation of the
consumption.
Current time
I Functions
time_t time (time_t *heure)
int stime (time_t *heure)
time returns the current time (or -1) and using the provided
address. stime modifies the current time (it is only accessible
by the admins) This sort of time is sometimes called wall
clock.
I gettimeofday
int gettimeofday (struct timeval *tv, struct timezone *
This function was provided by the University of Berkeley and it
is more accurate. A timeval data-structure contains 2 fields:
I time_t tv_sec : number of seconds since the Epoch
I suseconds_t tv_usec : number of microseconds
time is now a library function based on the primitive
gettimeofday.
Example
I Example
tv_sec = 1 500 000 000 and tv_usec = 123 456 This
corresponds to July 14th 2017 at 02:40:00 and 123 456
microseconds UTC.
I Code
time_t heure ;
struct tm * tm ;
char * s1 , s2 [ MAX ] ;
size_t n ;
heure = time ( NULL ) ;
tm = localtime (& heure ) ;
s1 = asctime ( tm ) ;
printf ( " maintenant : % s \ n " , s1 ) ;
n = strftime ( s2 , sizeof s2 ,
" date = % d /% m /% Y a % H :% M :% S " , tm )
if ( n == 0)
printf ( " s2 is too small \ n " ) ;
else printf ( " now : % s \ n " , s2 ) ;
Clock
int main () {
time_t rawtime;
struct tm *info;
time(&rawtime);
info = gmtime(&rawtime ); /* Get GMT time */