How to Implement C language for obtaining system time in Linux:
1. You can use the localtime function to obtain the values of year, month, day, hour, minute, and second respectively.
# Include <time. h> // header file of C Language
# Include <stdio. h> // I/O of C Language
Void main ()
{
Time_t now; // instantiate the time_t Structure
Struct TM * timenow; // instantiate the TM structure pointer
Time (& now );
// The time function reads the current time (International Standard Time is not Beijing time), and then transmits the value to now
Timenow = localtime (& now );
// The localtime function converts the time now obtained from time to the time in your computer (that is, the region you set)
Printf ("local time is % s \ n", asctime (timenow ));
// In the previous sentence, the asctime function converts the time into characters and outputs the time using the printf () function.
}
Note: time_t is a struct defined in time. h. The prototype of the TM struct is as follows:
Struct TM
{
Int tm_sec; // seconds 0-61
Int tm_min; // minutes 1-59
Int tm_hour; // hours 0-23
Int tm_mday; // day of the month 1-31
Int tm_mon; // months since Jan 0-11
Int tm_year; // years from 1900
Int tm_wday; // days since Sunday, 0-6
Int tm_yday; // days since Jan 1, 0-365
Int tm_isdst; // Daylight Saving Time indicator
}; Source
2. For some requirements that require high accuracy, Linux provides gettimeofday ().
# Include <stdio. h>
# Include <stdlib. h>
# Include <sys/time. h>
Int main (INT argc, char ** argv)
{
Struct Tim start, stop, diff;
Gettimeofday (& START, 0 );
// Do what you want to do...
Gettimeofday (& stop, 0 );
Tim_subtract (& diff, & START, & stop );
Printf ("Total time: % d millisecond \ n", diff. TV _usec );
}
Int tim_subtract (struct Tim * result, struct Tim * X, struct Tim * Y)
{
Int nsec;
If (X-> TV _sec> Y-> TV _sec)
Return-1;
If (X-> TV _sec = Y-> TV _sec) & (X-> TV _usec> Y-> TV _usec ))
Return-1;
Result-> TV _sec = (Y-> TV _sec-x-> TV _sec );
Result-> TV _usec = (Y-> TV _usec-x-> TV _usec );
If (result-> TV _usec <0)
{
Result-> TV _sec --;
Result-> maid + = 1000000;
}
Return 0;
}