search
HomeOperation and MaintenanceLinux Operation and MaintenanceDoes Linux have a function to calculate time?

Linux has functions for calculating time, such as: the function time() that can obtain the second-level time difference, the functions gettimeofday() and settimeofday() that can obtain the microsecond-level time difference, and the function that can obtain the nanosecond-level time difference. clock_gettime() and so on.

Does Linux have a function to calculate time?

#The operating environment of this tutorial: linux7.3 system, Dell G3 computer.

The following explains the time-related functions and time-conversion-related functions in Linux

1. Obtain time-related functions

1.1 Get the second-level time difference function

#include <time.h>
time_t time(time_t *timer);//通过函数返回值或者timer 变量均可以获取到当前时间

time_t is actually a long integer, representing UTC time (0:00:00 on January 1, 1970, Linux system The second-level time difference from Epoch time) to the current system time

1.2 Get the microsecond-level time difference function

#include <sys/time.h>
#include <unistd.h>
struct timeval {
    time_t       tv_sec;     /* seconds */
    suseconds_t tv_usec;    /* microseconds */
};

struct timezone{
 
    int tz_minuteswest; /*miniutes west of Greenwich*/
 
    int tz_dsttime; /*type of DST correction*/
 
};

//函数执行成功返回0,失败返回-1. 其中timezone 是时区相关的结构体
int gettimeofday(struct timeval *tv, struct timezone *tz);

//用来设置制定的时间和时区信息
int settimeofday(const struct timeval *tv, const struct timezone *gz);

1.3 Get the nanosecond-level time difference function

#include <time.h>

/*
其中clk_id 用来制定对应的时钟类型,不同的类型可以用来获取不同的时间值,具体有四种:
CLOCK_REALTIME: 			系统实时时间,从UTC开始计时,若时间被用户更改计数时间相应改变;
CLOCK_MONOTONIC:			从系统启动开始计时,即使用户更改时间也没有影响;
CLOCK_PROCESS_CPUTIME_ID:	本进程开始到执行到当前程序系统CPU花费的时间;
CLOCK_THREAD_CPUTIME_ID:	本线程开始到执行到当前程序系统CPU花费的时间

*/

struct timespec{
    time_t tv_sec;    //s
    long tv_nsec;    //ns
};

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

2. Convert time-related functions

2.1 Convert the time parameter time_t obtained by the above acquisition time function into a structure Body

struct tm, this structure contains very detailed fields such as year, month, day, etc. As shown below:

#include <time.h>
 
struct tm{
    int tm_sec;   //秒
    int tm_min;   //分
    int tm_hour;  //时;取值区间为[0, 23]
    int tm_mday;  //日;取值区间为[1, 31]
    int tm_mon;   //月份;取值区间为[0, 11]; 0表示1月份依次递增到12月份
    int tm_year;   //年份;其值为1900年至今年数
    int tm_wday;  //星期;0代表星期天,1代表星期1,以此类推
    int tm_yday;   //日期;0代表1月1日
    int tm_isdst;   //夏令时标识符;使用夏令时为正,不使用t为0,不确定时为负*/
};

The commonly used functions to convert time_t into struct tm structure are as follows:

#include <time.h> 
struct tm* gmtime(const time_t* timep);
struct tm*localtime(const time_t* timep);

gmtime() and localtime() functions can convert time_t data format into tm format type. The difference is that the result of the conversion by gmtime() is the information corresponding to GMT (central time zone), while the result of the conversion by the localtime() function is the information of the current time zone.

2.2 Convert time_t into the time and date strings we habitually use

The corresponding conversion function is as follows:

#include <time.h>
char* ctime(time_t* timep);

2.3 The corresponding function to convert struct tm into time_t

is as follows:

#include <time.h>
time_t mktime(struct tm *p_tm);

2.4 Convert struct tm into the time and date strings we habitually use

The corresponding functions are as follows:

#include <time.h>
char *asctime(const struct tm *p_tm); //习惯性字符串 Thu Dec  9 07:13:35 2021

2.5 Convert the time string into struct tm format

/**************************************
** description: 将struct tm 按照指定的format格式转化成字符串
** parameter:
		** *s : 需要被转换的时间字符串
		** *format:时间字符串的格式
		** *tm:转换后的tm时间
**************************************/
char *strptime(const char *s, const char *format, struct tm *tm);

2.6 Convert struct tm into a string according to the specified format

/**************************************
** description: 将struct tm 按照指定的format格式转化成字符串
** parameter:
		** *s : 生成的时间字符串
		** max: 字符串最大字符数(即最大可生成的字符数量)
		** *format:生成的字符串格式
		** *tm:需要被转换的tm时间
**************************************/
size_t strftime(char *s, size_t max, const char *format,const struct tm *tm);

3. Example

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

int main(int argc, char *argv[])
{	
	char *pstr = NULL;
	struct tm *ptm = NULL;

	printf("************** 使用ctime获取时间time_t **************\n");
	time_t times = 0;
	time(&times);
	printf("time_t:%ld\n\n", times);
	
	printf("************** 使用ctime转换time_t成我们习惯性使用的时间和日期字符串 **************\n");
	pstr = ctime(&times);
	printf("ctime:%s\n", pstr);
	
	printf("************** 使用gmtime转换time_t成struct tm 时间和日期**************\n");
	ptm = gmtime(&times);
	printf("time : %d:%d:%d\n", ptm->tm_hour,  ptm->tm_min,  ptm->tm_sec);
	printf("date: %d:%d:%d\n", ptm->tm_year+1900, ptm->tm_mon+1, ptm->tm_mday);
	printf("year: wday:%d yday:%d isdst:%d\n\n", ptm->tm_wday, ptm->tm_yday, ptm->tm_isdst);
	
	printf("************** 使用asctime转换struct tm成我们习惯性使用的时间和日期字符串**************\n");
	pstr = asctime(ptm);
	printf("asctime:%s\n\n", pstr);
	
	printf("************** 使用localtime转换time_t成struct tm 时间和日期**************\n");
	ptm = localtime(&times);
	printf("time : %d:%d:%d\n", ptm->tm_hour,  ptm->tm_min,  ptm->tm_sec);
	printf("date: %d:%d:%d\n", ptm->tm_year+1900, ptm->tm_mon+1, ptm->tm_mday);
	printf("year: wday:%d yday:%d isdst:%d\n", ptm->tm_wday, ptm->tm_yday, ptm->tm_isdst);

	pstr = asctime(ptm);
	printf("asctime:%s\n\n", pstr);

	printf("************** 使用gettimeofday获取微秒级的时间**************\n");
	struct timeval tv;
	struct timezone tz;
	gettimeofday(&tv, &tz);
	ptm = localtime(&tv.tv_sec);
	printf("time : %d:%d:%d\n", ptm->tm_hour,  ptm->tm_min,  ptm->tm_sec);
	printf("date: %d:%d:%d\n", ptm->tm_year+1900, ptm->tm_mon+1, ptm->tm_mday);
	printf("year: wday:%d yday:%d isdst:%d\n", ptm->tm_wday, ptm->tm_yday, ptm->tm_isdst);
	printf("tv_usec:%ld\n\n", tv.tv_usec);
	
	printf("************** 使用clock_gettime获取纳秒级的时间**************\n");
	struct timespec tp;
	clock_gettime(CLOCK_REALTIME, &tp);
	ptm = localtime(&tp.tv_sec);
	printf("time : %d:%d:%d\n", ptm->tm_hour,  ptm->tm_min,  ptm->tm_sec);
	printf("date: %d:%d:%d\n", ptm->tm_year+1900, ptm->tm_mon+1, ptm->tm_mday);
	printf("year: wday:%d yday:%d isdst:%d\n", ptm->tm_wday, ptm->tm_yday, ptm->tm_isdst);	
	printf("tp.tv_nsec:%ld\n\n", tp.tv_nsec);
	return 0;
}

Specific time character conversion

int str_to_time(void)
{
	char pstr[128] = {0};
    struct tm t;
    strptime("2021-04-23 12:34:56", "%Y-%m-%d %H:%M:%S", &t);
	
    printf("**** tm_isdst: %d, tm_yday:%d, tm_wday%d,\n %d-%d-%d \n %d:%d:%d\n", 
    t.tm_isdst, t.tm_yday, t.tm_wday, t.tm_year+1900, t.tm_mon+1, t.tm_mday,
    t.tm_hour, t.tm_min, t.tm_sec);
    printf("mktime ts:%ld\n", mktime(&t));
	printf("asctime:%s\n", asctime(&t));
	
	strftime(pstr, sizeof(pstr), "%Y-%m-%d %H:%M:%S", &t);
    printf("pstr:%s\n", pstr);
}

int time_to_str(void)
{
	char pstr[128] = {0};
    struct tm t = {
               .tm_sec = 56,    /* Seconds (0-60) */
               .tm_min = 34,    /* Minutes (0-59) */
               .tm_hour = 12,   /* Hours (0-23) */
               .tm_mday = 23,   /* Day of the month (1-31) */
               .tm_mon = 4-1,     /* Month (0-11) */
               .tm_year = 2021-1900,   /* Year - 1900 */
               .tm_wday = 5,     /* Day of the week (0-6, Sunday = 0) */
               .tm_yday = 113,   /* Day in the year (0-365, 1 Jan = 0) */
               .tm_isdst = 0,    /* Daylight saving time */
           };
    strftime(pstr, sizeof(pstr), "%Y-%m-%d %H:%M:%S", &t);
    printf("pstr:%s\n", pstr);
}

If you want to Get the time since system startup, even if the user changes the time, there will be no impact, in milliseconds, for example:

unsigned long long clock_systick_get(void)
{
    int ret = -1;
    unsigned long long time;
    int cnt = 0;
    struct timespec  now = {0, 0};

    while (ret < 0 && cnt < 3)
    {
        ret = clock_gettime(CLOCK_MONOTONIC, &now);	//获取失败重试,最大执行3次
        cnt++;
    }
    time = now.tv_sec * 1000 + now.tv_nsec / (1000000);
    return time;
}

Related recommendations: "Linux Video Tutorial"

The above is the detailed content of Does Linux have a function to calculate time?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Linux Operations: Utilizing the Maintenance ModeLinux Operations: Utilizing the Maintenance ModeApr 19, 2025 am 12:08 AM

Linux maintenance mode can be entered through the GRUB menu. The specific steps are: 1) Select the kernel in the GRUB menu and press 'e' to edit, 2) Add 'single' or '1' at the end of the 'linux' line, 3) Press Ctrl X to start. Maintenance mode provides a secure environment for tasks such as system repair, password reset and system upgrade.

Linux: How to Enter Recovery Mode (and Maintenance)Linux: How to Enter Recovery Mode (and Maintenance)Apr 18, 2025 am 12:05 AM

The steps to enter Linux recovery mode are: 1. Restart the system and press the specific key to enter the GRUB menu; 2. Select the option with (recoverymode); 3. Select the operation in the recovery mode menu, such as fsck or root. Recovery mode allows you to start the system in single-user mode, perform file system checks and repairs, edit configuration files, and other operations to help solve system problems.

Linux's Essential Components: Explained for BeginnersLinux's Essential Components: Explained for BeginnersApr 17, 2025 am 12:08 AM

The core components of Linux include the kernel, file system, shell and common tools. 1. The kernel manages hardware resources and provides basic services. 2. The file system organizes and stores data. 3. Shell is the interface for users to interact with the system. 4. Common tools help complete daily tasks.

Linux: A Look at Its Fundamental StructureLinux: A Look at Its Fundamental StructureApr 16, 2025 am 12:01 AM

The basic structure of Linux includes the kernel, file system, and shell. 1) Kernel management hardware resources and use uname-r to view the version. 2) The EXT4 file system supports large files and logs and is created using mkfs.ext4. 3) Shell provides command line interaction such as Bash, and lists files using ls-l.

Linux Operations: System Administration and MaintenanceLinux Operations: System Administration and MaintenanceApr 15, 2025 am 12:10 AM

The key steps in Linux system management and maintenance include: 1) Master the basic knowledge, such as file system structure and user management; 2) Carry out system monitoring and resource management, use top, htop and other tools; 3) Use system logs to troubleshoot, use journalctl and other tools; 4) Write automated scripts and task scheduling, use cron tools; 5) implement security management and protection, configure firewalls through iptables; 6) Carry out performance optimization and best practices, adjust kernel parameters and develop good habits.

Understanding Linux's Maintenance Mode: The EssentialsUnderstanding Linux's Maintenance Mode: The EssentialsApr 14, 2025 am 12:04 AM

Linux maintenance mode is entered by adding init=/bin/bash or single parameters at startup. 1. Enter maintenance mode: Edit the GRUB menu and add startup parameters. 2. Remount the file system to read and write mode: mount-oremount,rw/. 3. Repair the file system: Use the fsck command, such as fsck/dev/sda1. 4. Back up the data and operate with caution to avoid data loss.

How Debian improves Hadoop data processing speedHow Debian improves Hadoop data processing speedApr 13, 2025 am 11:54 AM

This article discusses how to improve Hadoop data processing efficiency on Debian systems. Optimization strategies cover hardware upgrades, operating system parameter adjustments, Hadoop configuration modifications, and the use of efficient algorithms and tools. 1. Hardware resource strengthening ensures that all nodes have consistent hardware configurations, especially paying attention to CPU, memory and network equipment performance. Choosing high-performance hardware components is essential to improve overall processing speed. 2. Operating system tunes file descriptors and network connections: Modify the /etc/security/limits.conf file to increase the upper limit of file descriptors and network connections allowed to be opened at the same time by the system. JVM parameter adjustment: Adjust in hadoop-env.sh file

How to learn Debian syslogHow to learn Debian syslogApr 13, 2025 am 11:51 AM

This guide will guide you to learn how to use Syslog in Debian systems. Syslog is a key service in Linux systems for logging system and application log messages. It helps administrators monitor and analyze system activity to quickly identify and resolve problems. 1. Basic knowledge of Syslog The core functions of Syslog include: centrally collecting and managing log messages; supporting multiple log output formats and target locations (such as files or networks); providing real-time log viewing and filtering functions. 2. Install and configure Syslog (using Rsyslog) The Debian system uses Rsyslog by default. You can install it with the following command: sudoaptupdatesud

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.