The time function of Linux acquisition and the calculation difference

Source: Internet
Author: User
Tags posix string format

Reference: http://www.cnblogs.com/krythur/archive/2013/02/25/2932647.html


The first chapter gets the time function


1. Char * asctime (const struct TM * timeptr);

Function description
Asctime () Converts the information in the TM structure referred to by the parameter timeptr to the time-date representation used by the real world, and then returns the result in string form. This function has been converted from time zone to local time, and the string format is: "Wed June 21:49:08 1993\n"

return value
If the associated time-date function is called again, the string may be corrupted. This function differs from CTime in that the parameters passed in are different structures.

Additional Instructions
Returns a string representing the current local time date.

Example
#include <time.h>
Main ()
{
time_t TIMEP;
Time (&TIMEP);
printf ("%s", Asctime (Gmtime (&TIMEP)));
}

Perform
Sat Oct 28 02:10:06 2000

2. Defining functions
Char *ctime (const time_t *TIMEP);

Function description
CTime () Converts the information in the time_t structure referred to by the parameter TIMEP to the time-date representation used by the real world, and then returns the result in string form. This function has been converted from time zone to local time, and the string format is "Wed June 21:49:08 1993\n". If the associated time-date function is called again, the string may be corrupted.

return value
Returns a string representing the current local time date.

Example
#include <time.h>
Main ()
{
time_t TIMEP;
Time (&TIMEP);
printf ("%s", CTime (&TIMEP));
}

Perform
Sat Oct 28 10:12:05 2000

3. struct Tm*gmtime (const TIME_T*TIMEP);

Function description
Gmtime () Converts the information in the time_t structure referred to by the parameter TIMEP to the time-date representation used by the real world, and then returns the result from the Fabric TM.
The structure TM is defined as
struct TM
{
int tm_sec;
int tm_min;
int tm_hour;
int tm_mday;
int Tm_mon;
int tm_year;
int tm_wday;
int tm_yday;
int tm_isdst;
};
The int tm_sec represents the current number of seconds, the normal range is 0-59, but is allowed to 61 seconds
int Tm_min represents current score, range 0-59
int Tm_hour The number of hours from midnight, with a range of 0-23
int Tm_mday The number of days in the current month, range 01-31
The int Tm_mon represents the current month, starting from January, ranging from 0-11
int tm_year number of years since 1900
int Tm_wday The number of days of the week, starting from Monday, with a range of 0-6
int Tm_yday The number of days since January 1 this year, ranging from 0-365
int TM_ISDST Daylight Saving time flag
The time date returned by this function is not converted by the time zone, but UTC time.

return value
Returns the structure TM representing the current UTC time

Example
#include <time.h>
Main () {
Char *wday[]={"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
time_t TIMEP;
struct TM *p;
Time (&AMP;TIMEP);
P=gmtime (&AMP;TIMEP);
printf ("%d%d%d", (1900+p->tm_year), (1+p->tm_mon), p->tm_mday);
printf ("%s%d;%d;%d\n", Wday[p->tm_wday], P->tm_hour, P->tm_min, p->tm_sec);
}

Perform
2000/10/28 Sat 8:15:38

4.  struct TM *localtime (const time_t * TIMEP); The
 
function describes
 localtime () converts the information in the time_t structure referred to by the parameter TIMEP to the time-date representation used by the real world, and then returns the result from the Fabric TM. Please refer to Gmtime () for the definition of structure TM. The time date returned by this function has been converted to the local time zone.
 
return value
  Return structure TM represents the current local time.
 
Example
  #include <time.h>
Main () {
char *wday[]={"Sun", "Mon", "Tue", "Wed", "Thu", "Fri "," Sat "};
time_t TIMEP;
Struct TM *p;
Time (&TIMEP);
P=localtime (&TIMEP);/* Get local time */
printf ("%d%d%d", (1900+p->tm_year), (L+p->tm_mon), P->tm_mday) ;
printf ("%s%d:%d:%d\n", Wday[p->tm_wday],p->tm_hour, P->tm_min, p->tm_sec);
}
 
Execute
 2000/10/28 Sat 11:12:22

5. time_t mktime (Strcut TM * timeptr);

Function description
The Mktime () is used to convert the TM structure data referred to by the parameter timeptr to the number of seconds elapsed since the UTC time of January 1, 1970 0:0 0 seconds.

return value
Returns the number of seconds elapsed.

Example
/* Take time (in seconds) using localtime ()
Convert to a struct TM and then use Mktine () to convert the struct TM to the original number of seconds */
#include <time.h>
Main ()
{
time_t TIMEP;
Strcut TM *p;
Time (&TIMEP);
printf ("Time ():%d \ n", TIMEP);
P=localtime (&TIMEP);
TIMEP = Mktime (p);
printf ("Time ()->localtime ()->mktime ():%d\n", TIMEP);
}

Perform
Time (): 974943297
Time ()->localtime ()->mktime (): 974943297


6. time_t time (time_t *t);

Function description
This function returns the number of seconds from 0:0 to 0 seconds since the UTC time in A.D. January 1, 1970. If T is not a null pointer, this function also saves the return value to the memory referred to by the T-pointer.

return value
Success returns the number of seconds, and failure returns the ((time_t)-1) value, which causes the error to exist in errno.

Example
#include <time.h>
Mian ()
{
int seconds= time ((time_t*) NULL);
printf ("%d\n", seconds);
}

7. Gettimeofday (): Can obtain the subtle level (0.000001 seconds) of the system time, call two times gettimeofday (), do subtraction before and after, so as to achieve the purpose of timing or calculation time.


Char *asctime (const struct TM *TM);

Char *asctime_r (const struct TM *tm, char *buf);

Char *ctime (const time_t *TIMEP);

Char *ctime_r (const time_t *TIMEP, char *buf);

struct TM *gmtime (const time_t *TIMEP); acquired for the British time

struct TM *gmtime_r (const time_t *TIMEP, struct TM *result);

struct TM *localtime (const time_t *TIMEP); get a local time , Note the difference from the UK time.

struct TM *localtime_r (const time_t *TIMEP, struct TM *result);

time_t mktime (struct TM *tm);

Double difftime (time_t time1, time_t TIME0);

int gettimeofday (struct timeval *tv, struct timezone *tz);

int settimeofday (const struct Timeval *tv, const struct timezone *tz);



The second chapter calculates the time difference

1. Real-time function Clock_gettime unit is One-zero seconds, that is nanosecond (NS), using the standard POSIX real-time clock, calculated results may have errors.

This function is added to the POSIX1003.1, and its prototype is as follows:

int Clock_gettime (clockid_t clk_id, struct timespec *tp);

It has the following characteristics:
1) It also has a time structure: Timespec, Timespec calculates the number of times in units of one-zero seconds.
Strace timespec{
time_t tv_sec;
Long tv_nsec;
}

2) clockid_t is to determine which clock type.

Clock_realtime: Standard POSIX real-time clock
Clock_monotonic:posix Clock, operates at a constant rate, does not reset and adjusts, and its value is the same as clock_realtime.
CLOCK_PROCESS_CPUTIME_ID and clock_thread_cputime_id are implemented in the hardware timers in the CPU.


3) Test:
#include <time.h>
#include <stdio.h>
#include <stdlib.h>

#define MILLION 1000000


int main (void)
{
long int loop = 1000;
struct Timespec tpstart;
struct Timespec tpend;
Long timedif;

Clock_gettime (Clock_monotonic, &tpstart);

while (--loop) {
System ("CD");
}

Clock_gettime (Clock_monotonic, &tpend);
Timedif = million* (tpend.tv_sec-tpstart.tv_sec) + (TPEND.TV_NSEC-TPSTART.TV_NSEC)/1000;
fprintf (stdout, "It took%ld microseconds\n", timedif);

return 0;
}

Compile:
GCC Test3.c-lrt-o test3

Calculation time:
Time./test3
It took 3463843 microseconds



2. int gettimeofday (struct timeval *tv,struct Timezone*tz) will return the structure that the current time TV refers to, and the local time zone information is placed in the structure referred to by TZ .  Both of these structures are placed in the/usr/include/sys/time.h. units microseconds (μs)

#include <stdio.h>
#include <stdlib.h> //malloc to use, if not, there will be a warning message: An implicit declaration is incompatible with the built-in function ' malloc '. But the warning message is fine .

#include <assert.h>
#include <sys/time.h>

int main ()
{
float time_use=0;
struct Timeval start;
struct Timeval end;
struct timezone tz; It's explained later.
Gettimeofday (&start,null); Gettimeofday (&start,&tz);
printf ("start.tv_sec:%d\n", start.tv_sec);
printf ("start.tv_usec:%d\n", start.tv_usec);

Sleep (3);
Gettimeofday (&end,null);
printf ("end.tv_sec:%d\n", end.tv_sec);
printf ("end.tv_usec:%d\n", end.tv_usec);
Time_use= (end.tv_sec-start.tv_sec) *1000000+ (end.tv_usec-start.tv_usec);//microseconds
printf ("Time_use is%f\n", time_use);

Output: Time_use is 3001410.000000

The following pointers can also be used, but be aware that the pointer type is compiled correctly if memory is not allocated, but the result of the operation is not


}


3. #include <sys/times.h>
clock_t Times (struct TMS *buf); The Unit 10 ms (MS) Times is actually called clock () implementation.

The Times () function returns the number of clocks that have elapsed from an arbitrary point in the past. The return value may exceed the range (overflow) of clock_t (typically long). If an error occurs, the (clock_t)-1 type is returned, and the corresponding errno value is set.

The system clocks per second can be obtained by sysconf (_SC_CLK_TCK);


The TMS structure is as follows:
Strace tms{
clock_t Tms_utime;
clock_t Tms_stime;
clock_t Tms_cutime;
clock_t Tms_cstime;
}

Comments:
Tms_utime records the time that the process executes the user code.
Tms_stime records the time that the process executed the kernel code.
Tms_cutime records the time that the child process executes the user code.
Tms_cstime records the time that the child process executes the kernel code.


2) Test:

VI test2.c
#include <sys/times.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

static void Do_cmd (char *);
static void Pr_times (clock_t, struct TMS *, struct TMS *);

int main (int argc, char *argv[]) {
int i;
for (I=1; argv[i]!=null; i++) {
Do_cmd (Argv[i]);
}
Exit (1);
}
static void Do_cmd (char *cmd) {
struct TMS Tmsstart, tmsend;
clock_t start, end;
int status;
if ((Start=times (&tmsstart)) = =-1)
Puts ("Times error");
if ((Status=system (cmd)) <0)
Puts ("system error");
if ((End=times (&tmsend)) = =-1)
Puts ("Times error");
Pr_times (End-start, &tmsstart, &tmsend);
Exit (0);
}
static void Pr_times (clock_t real, struct TMS *tmsstart, struct TMS *tmsend) {
static long clktck=0;
if (0 = = CLKTCK)
if ((clktck=sysconf (_SC_CLK_TCK)) <0)
Puts ("sysconf err");
printf ("real:%7.2f\n", real/(double) clktck);
printf ("user-cpu:%7.2f\n", (tmsend->tms_utime-tmsstart->tms_utime)/(double) clktck);
printf ("system-cpu:%7.2f\n", (tmsend->tms_stime-tmsstart->tms_stime)/(double) clktck);
printf ("child-user-cpu:%7.2f\n", (tmsend->tms_cutime-tmsstart->tms_cutime)/(double) clktck);
printf ("child-system-cpu:%7.2f\n", (tmsend->tms_cstime-tmsstart->tms_cstime)/(double) clktck);
}

Compile:
GCC Test2.c-o test2

Test this program:
Time./test2 "dd If=/dev/zero f=/dev/null bs=1m count=10000"
10000+0 Records in
10000+0 Records out
10485760000 bytes (Ten GB) copied, 4.93028 s, 2.1 GB/s
real:4.94
user-cpu:0.00
system-cpu:0.00
child-user-cpu:0.01
child-system-cpu:4.82


4. #include <time.h>

clock_t clock (void); Unit 10 ms (MS)

clk_id , struct Timespec * TP ); sysconf (_SC_CLK_TCK); function is obtained.

Chapter III Summary

1) Accuracy comparison:

The following are type conversions for various types of precision:
1 seconds =1000 milliseconds (ms), 1 milliseconds =1/1000 seconds (s);
1 seconds =1000000 microseconds (μs), 1 microseconds =1/1000000 seconds (s);
1 sec =1000000000 ns, 1 nanoseconds =1/1000000000 sec (s);


2)
The accuracy of the clock () function is 10 milliseconds (ms)
Times () The accuracy of the function is 10 milliseconds (ms)
The accuracy of the gettimofday () function is microseconds (μs)
The unit of measure for the Clock_gettime () function is One-zero, which is the nanosecond (NS)


3) times () and clock ()

The default Linux clock cycle is 100HZ, and now the latest kernel clock cycle defaults to 250HZ.
How do I get the clock cycle of the kernel?
grep ^config_hz/boot/config-2.6.26-1-xen-amd64

Config_hz_250=y
config_hz=250

The result is 250HZ.

And with sysconf (_SC_CLK_TCK), you get 100HZ.
For example:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <sys/times.h>
#include <sys/time.h>

Int
Main (int argc, char *argv[])
{

Long TPS = sysconf (_SC_CLK_TCK);
printf ("%ld\n", TPs);

return exit_success;
}

Why do we get a different value?
Because Sysconf (_SC_CLK_TCK) and config_hz represent different meanings.
Sysconf (_SC_CLK_TCK) is the clock_t frequency of the GNU Standard Library.
It is defined in the following position:/usr/include/asm/param.h

For example:
#ifndef HZ
#define HZ 100
#endif

Finally, summarize the kernel time:
The standard time for the kernel is jiffy, a jiffy is an internal clock cycle, and the internal clock cycle is generated by the frequency of 250HZ, which is a clock tick, with a interval of 4 milliseconds (ms).

Other words:
1 jiffy=1 internal clock cycles =250hz=1 clock ticks = 4 milliseconds

Sysconf (_SC_CLK_TCK) uses the default Linux clock cycle is 100HZ, 1 jiffy=1 internal clock cycles =100hz=1 clock ticks = 10 milliseconds, so the latest unit of clock () and times () is 10ms

A clock interrupt handler is called every time a tick is passed, and the handler uses Jiffy to accumulate the clock ticks, which increases by 1 for each time a clock interrupt occurs.
After each interrupt, the system chooses whether the process will continue to run or let the process go into a ready state through the scheduler with the time slice.




The time function of Linux acquisition and the calculation difference

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.