How to obtain and use time in Linux system

How to obtain and use time in Linux system

There are two types of Linux system time.

(1) Calendar time. The value is the cumulative number of seconds that have elapsed since the specified time, 00:00:00, January 1, 1970 Coordinated Universal Time (UTC). Basic data types are stored using time_t. Finally, through conversion, we can get the 24-hour or 12-hour time that we usually see.

(2) Process time. Also known as CPU time, it measures the central processing unit resources used by a process. Process time is measured in clock ticks.

This article will give you a detailed introduction on how to obtain and use Linux time. Let's take a look at the detailed introduction.

Get Timestamp

time()

#include <time.h>
time_t time(time_t *calptr)
  • time returns the current time stamp, which is the number of seconds from universal time to now;
  • time_t is actually a uint64_t;
  • When calptr is not empty, the timestamp will also be written into the pointer;

Calling example:

#include <time.h>
#include <iostream>
#include <stdlib.h>

using namespace std;

int main()
{
time_t curTime;
curTime = time(NULL);
cout << curTime << endl;
return 0;
}

result:

Returns a string of values, such as 1533287924

gettimeofday() and clock_gettime()

The time function can only get the time with precision of seconds. To get a timestamp with higher precision, other functions are needed. The gettimeofday function can obtain a timestamp with microsecond precision and save it in the timeval structure; the clock_gettime function can obtain a timestamp with nanosecond precision and save it in the timespec structure.

#include <sys/time.h>

int gettimeofday(struct timeval *tp, void *tzp);
For historical reasons, the only legal value for tzp is NULL, so just write NULL when calling it.

int clock_gettime(clockid_t clock_id, strcut timespec *tsp);
clock_id has multiple options. When CLOCK_REALTIME is selected, the function is similar to time, but the time accuracy is higher.

The structures used by the two functions are defined as follows:

struct timeval
{
long tv_sec; /*seconds*/
long tv_usec; ​​/*microseconds*/
};

struct timespec
{
time_t tv_sec; //seconds long tv_nsec; //nanoseconds};

Calling example:

#include <time.h>
#include <sys/time.h>
#include <iostream>
#include <stdlib.h>

using namespace std;

int main()
{
time_t dwCurTime1;
dwCurTime1 = time(NULL);

struct timeval stCurTime2;
gettimeofday(&stCurTime2, NULL);

struct timespec stCurTime3;
clock_gettime(CLOCK_REALTIME, &stCurTime3);

cout << "Time1: " << dwCurTime1 << "s" << endl;
cout << "Time2: " << stCurTime2.tv_sec << "s, " << stCurTime2.tv_usec << "us" << endl;
cout << "Time3: " << stCurTime3.tv_sec << "s, " << stCurTime3.tv_nsec << "ns" << endl;

return 0;
}

result:

When compiling, add -lrt to the end of the compile command to link the Real Time dynamic library, such as
g++ -o time2 test_time_linux_2.cpp -lrt

Time1: 1533289490s
Time2: 1533289490s, 133547us
Time3: 1533289490s, 133550060ns

Visualizing time

tm structure

The obtained timestamp cannot intuitively display the current time. Therefore, we need to use the tm structure to represent the time we see in daily life. The structure is defined as follows:

struct tm
{
int tm_sec; /*Seconds, normal range 0-59, but up to 61 is allowed*/
int tm_min; /*minute, 0-59*/
int tm_hour; /*hour, 0-23*/
int tm_mday; /*Day, that is, the day of the month, 1-31*/
int tm_mon; /*Month, starting from January, 0-11*/ 1+p->tm_mon;
int tm_year; /*year, how many years have passed since 1900*/ 1900+ p->tm_year;
int tm_wday; /*Week, day of the week, starting from Sunday, 0-6*/
int tm_yday; /*The number of days from January 1st of this year to the present, ranging from 0 to 365*/
int tm_isdst; /*Daylight saving time flag*/
};

time_t to tm

gmtime and localtime can convert time_t type timestamps into tm structures. The usage is as follows:

struct tm* gmtime(const time_t *timep);
//Convert the time represented by time_t to UTC time without time zone conversion, which is a struct tm structure pointer stuct tm* localtime(const time_t *timep);
//Similar to gmtime, but it is the time after time zone conversion, that is, it can be converted to Beijing time.

Fixed format printing time

After obtaining the tm structure, you can convert it into a string format for daily use, or convert it directly from time_t. You can use the following two functions to achieve this purpose. However, these two functions can only print time in a fixed format.

//These two functions have been marked as deprecated. Try to use the functions that will be introduced later. char *asctime(const struct tm* timeptr);
char *ctime(const time_t *timep);

Calling example:

#include <time.h>
#include <sys/time.h>
#include <iostream>
#include <stdlib.h>

using namespace std;

int main()
{
time_t dwCurTime1;
dwCurTime1 = time(NULL);

struct tm* pTime;
pTime = localtime(&dwCurTime1);

char* strTime1;
char* strTime2;
strTime1 = asctime(pTime);
strTime2 = ctime(&dwCurTime1);

cout << strTime1 << endl;
cout << strTime2 << endl;

return 0;
}

result:

Fri Aug 3 18:24:29 2018
Fri Aug 3 18:24:29 2018

Flexible and safe time conversion function strftime()

The above two functions are marked as deprecated because of possible buffer overflow issues, so a safer method is to use the strftime method.

/*
** @buf: Store output time ** @maxsize: Maximum byte length of the buffer ** @format: Specify the format of output time ** @tmptr: Pointer to structure tm*/
size_t strftime(char* buf, size_t maxsize, const char *format, const struct tm *tmptr);

We can output the time information stored in timeptr to buf according to the format specified by format according to the format in the string pointed to by format, and store at most maxsize characters in the buffer buf. This function returns the number of characters placed into the string pointed to by buf.

The strftime() function operates somewhat similarly to sprintf(): it recognizes a set of format commands that begin with a percent sign (%) and formats the output in a string. The format command specifies the exact representation of various date and time information in the string strDest. The other characters in the format string are placed into the string unchanged. The format commands are listed below and are case sensitive.

%a Abbreviation for the day of the week
%A Full name of the day of the week
%b Abbreviation for month
%B Full name of the month
%c Standard date and time string
%C The last two digits of the year
%d The day of the month in decimal notation
%D Month/Day/Year
%e Day of the month as decimal in a two-character field
%F Year-Month-Day
%g Last two digits of the year, using week-based year
%G Year, using week-based years
%h abbreviated month name
%H Hour in 24-hour format
%I Hour in 12-hour format
%j The day of the year in decimal notation
%m Month in decimal notation
%M Minutes in ten-hour format
%n Newline character
%p The locale's equivalent of AM or PM
%r 12 hours of time
%R displays hours and minutes: hh:mm
%S Decimal seconds
%t horizontal tab character
%T displays hours, minutes, and seconds: hh:mm:ss
%u The day of the week, with Monday as the first day (values ​​from 0 to 6, with Monday as 0)
%U Week number of the year, with Sunday as the first day (values ​​from 0 to 53)
%V Week of the year, using week-based year
%w The day of the week as a decimal number (values ​​from 0 to 6, with Sunday as 0)
%W Week number of the year, with Monday as the first day (values ​​from 0 to 53)
%x Standard date string
%X Standard time string
%y Decimal year without century (values ​​from 0 to 99)
%Y Decimal year with century
%z, %Z Time zone name. If the time zone name cannot be obtained, an empty character is returned.
%% Percent sign

Calling example:

#include <time.h>
#include <sys/time.h>
#include <iostream>
#include <stdlib.h>

using namespace std;

int main()
{
time_t dwCurTime1;
dwCurTime1 = time(NULL);

struct tm* pTime;
pTime = localtime(&dwCurTime1);

char buf[100];

strftime(buf, 100, "time: %r, %a %b %d, %Y", pTime);

cout << buf << endl;

return 0;
}

result:

time: 08:18:12 PM, Fri Aug 03, 2018

Graph of the relationship between time functions

Process time

Process time is the time the process uses the CPU after it is created. Process time is divided into the following two parts:

  • User CPU time: The time spent using the CPU in user mode
  • Kernel CPU time: The time spent using the CPU in kernel mode. This is the time required to execute kernel calls or other special tasks.

clock function

The clock function provides a simple interface for obtaining process time. It returns a value describing the total CPU time (including user time and kernel time) used by the process. The function is defined as follows:

#include <time.h>
clock_t clock(void)
//if error, return -1

The clock function returns a value in CLOCKS_PER_SEC units. Dividing the return value by this unit gives the number of seconds of the process time.

times Function

The times function is also a process time function, which has a more specific process time representation. The function definition is as follows:

#include <sys/times.h>
clock_t times(struct tms* buf);

struct tms{
clock_t tms_utime;
clock_t tms_stime;
clock_t tms_cutime;
clock_t tms_cstime;
};

Although the return type of the times function is still clock_t, the unit of measurement of the return value is different from that of the clock function. The measurement unit of the return value of the times function can be obtained through sysconf (SC_CLK_TCK).

A complete use case in the Linux System Programming Manual is as follows:

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

static void displayProcessTime(const char* msg)
{
struct tms t;
clock_t clockTime;
static long clockTick = 0;

if (msg != NULL) 
{
printf("%s\n", msg);
}

if (clockTick == 0)
{
clockTick = sysconf(_SC_CLK_TCK);
if (clockTick < 0) return;
}

clockTime = clock();
printf("clock return %ld CLOCKS_PER_SEC (%.2f seconds)\n", (long)clockTime, (double)clockTime/CLOCKS_PER_SEC);

times(&t);
printf("times return user CPU = %.2f; system CPU = %.2f\n", (double)t.tms_utime / clockTick, (double)t.tms_stime / clockTick);
}

int main()
{
printf("CLOCKS_PER_SEC = %ld, sysconf(_SC_CLK_TCK) = %ld\n", (long)CLOCKS_PER_SEC, sysconf(_SC_CLK_TCK));

displayProcessTime("start:");
for (int i = 0; i < 1000000000; ++i)
{
getpid();
}
printf("\n");
displayProcessTime("end:");

return 0;
}

refer to

[1] http://www.runoob.com/w3cnote/cpp-time_t.html

[2] Advanced Unix Programming Environment (3rd Edition)

[3] Unix System Programming Manual

Summarize

The above is the full content of this article. I hope that the content of this article will have certain reference learning value for your study or work. If you have any questions, you can leave a message to communicate. Thank you for your support for 123WORDPRESS.COM.

You may also be interested in:
  • How to generate files named with current time under Windows and Linux
  • Date command under Linux, formatted output, time setting method
  • Parsing the time function under Linux: how to set and get the time
  • Linux batch delete file command by time (delete files N days ago)
  • Linux obtains the process execution time method example
  • How to get the Linux system startup time in the program
  • Detailed explanation of the time acquisition function based on Linux
  • Detailed explanation of Linux system boot time example
  • Linux determines the file modification time and system time difference
  • Linux/Unix command lines about time and timestamps

<<:  Using JS to determine the existence of elements in an array in ten minutes

>>:  Solution to ERROR 1366 when entering Chinese in MySQL

Recommend

Example of how to configure multiple virtual hosts in nginx

It is very convenient to configure virtual host v...

CSS to achieve text on the background image

Effect: <div class="imgs"> <!-...

How does MySQL ensure master-slave consistency?

Table of contents The basic principle of MySQL ma...

Vue implements page caching function

This article example shares the specific code of ...

Detailed explanation of sql_mode mode example in MySQL

This article describes the sql_mode mode in MySQL...

Install JDK8 in rpm mode on CentOS7

After CentOS 7 is successfully installed, OpenJDK...

Detailed explanation of html printing related operations and implementation

The principle is to call the window.print() metho...

JavaScript to achieve lottery effect

This article shares the specific code of JavaScri...

Implementation of tomcat image created with dockerfile based on alpine

1. Download the alpine image [root@docker43 ~]# d...

How to query the latest transaction ID in MySQL

Written in front: Sometimes you may need to view ...

Common properties of frameset (dividing frames and windows)

A frame is a web page screen divided into several ...