搜尋
首頁運維linux運維linux有計算時間的函數嗎

linux有計算時間的函數,例如:可取得秒級時間差的函數time()、可取得微秒時間差的函數gettimeofday()和settimeofday()、可取得奈秒時間差的函數clock_gettime()等等。

linux有計算時間的函數嗎

本教學操作環境:linux7.3系統、Dell G3電腦。

下面講解的是linux中時間相關的函數和將時間轉換相關函數

#1.取得時間相關函數

1.1 取得秒級時間差函數

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

time_t其實是長整型,表示UTC時間(1970年1月1日0時0分0秒,Linux系統的Epoch時間)到目前系統時間的秒數級時間差

#1.2 取得微秒時間差函數

#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取得奈秒時間差函數

#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.轉換時間相關函數

#2.1將上述取得時間函數取得到的時間參數time_t轉換為結構體

struct tm,該結構體包含年月日等非常詳細的域。下如圖所示:

#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,不确定时为负*/
};

將time_t轉換成struct tm結構體常用的函數如下:

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

gmtime() 和localtime() 函數可以將time_t 資料格式轉換成tm格式的類型。差異在於gmtime()轉換的結果是GMT(中央時區)對應的訊息,而localtime() 函數轉換的結果是目前所在時區的資訊。

2.2將time_t轉換成我們習慣性使用的時間與日期字串

#對應轉換函數如下:

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

2.3 將struct tm 轉換成time_t

對應函數如下:

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

2.4將struct tm轉換成我們習慣性使用的時間和日期字串

#對應函數如下:

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

2.5 將時間字串轉換成struct tm格式

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

2.6 將struct tm 依照指定的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.舉例

#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;
}

特定的時間字元互相轉換

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);
}

若想取得從系統啟動開始計時,即使使用者更改時間也沒有影響的時間,單位毫秒,舉例如下:

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;
}

相關推薦:《Linux影片教學

#

以上是linux有計算時間的函數嗎的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
掌握Linux操作:實用指南掌握Linux操作:實用指南Apr 12, 2025 am 12:10 AM

掌握Linux操作的原因是其廣泛的應用場景和強大的功能。 1)Linux適合開發者、系統管理員和技術愛好者,應用於服務器管理、嵌入式系統和容器化技術。 2)學習Linux可以從文件系統結構、Shell使用、用戶權限管理和進程管理入手。 3)Linux命令行是其核心工具,通過Shell執行命令,如ls、mkdir、cd等,支持重定向和管道操作。 4)高級用法包括編寫自動化腳本,如備份腳本,使用tar命令和條件判斷。 5)常見錯誤包括權限、路徑和語法問題,可通過echo、set-x和$?調試。 6)性能優化建議

Linux的5支支柱:了解他們的角色Linux的5支支柱:了解他們的角色Apr 11, 2025 am 12:07 AM

Linux系統的五大支柱是:1.內核,2.系統庫,3.Shell,4.文件系統,5.系統工具。內核管理硬件資源並提供基本服務;系統庫為應用程序提供預編譯函數;Shell是用戶與系統交互的接口;文件系統組織和存儲數據;系統工具用於系統管理和維護。

Linux維護模式:工具和技術Linux維護模式:工具和技術Apr 10, 2025 am 09:42 AM

在Linux系統中,可以通過在啟動時按特定鍵或使用命令如“sudosystemctlrescue”進入維護模式。維護模式允許管理員在不受干擾的情況下進行系統維護和故障排除,如修復文件系統、重置密碼、修補安全漏洞等。

關鍵Linux操作:初學者指南關鍵Linux操作:初學者指南Apr 09, 2025 pm 04:09 PM

Linux初學者應掌握文件管理、用戶管理和網絡配置等基本操作。 1)文件管理:使用mkdir、touch、ls、rm、mv、cp命令。 2)用戶管理:使用useradd、passwd、userdel、usermod命令。 3)網絡配置:使用ifconfig、echo、ufw命令。這些操作是Linux系統管理的基礎,熟練掌握它們可以有效管理系統。

如何使用sudo向Linux的用戶授予高架特權?如何使用sudo向Linux的用戶授予高架特權?Mar 17, 2025 pm 05:32 PM

本文解釋瞭如何管理Linux中的Sudo特權,包括授予,撤銷和安全性最佳實踐。關鍵重點是安全和sudoers安全和限制訪問。Character數量:159

如何在Linux中實現SSH的兩因素身份驗證(2FA)?如何在Linux中實現SSH的兩因素身份驗證(2FA)?Mar 17, 2025 pm 05:31 PM

本文提供了有關使用Google Authenticator在Linux上設置兩因素身份驗證(2FA)的指南,詳細介紹了安裝,配置和故障排除步驟。它突出了2FA的安全益處,例如增強的SEC

如何使用TOP,HTOP和VMSTAT等工具來監視Linux中的系統性能?如何使用TOP,HTOP和VMSTAT等工具來監視Linux中的系統性能?Mar 17, 2025 pm 05:28 PM

本文討論了使用TOP,HTOP和VMSTAT監視Linux系統性能,並詳細介紹其獨特功能和自定義選項,以進行有效的系統管理。

如何使用軟件包管理器(APT,YUM,DNF)管理Linux中的軟件包?如何使用軟件包管理器(APT,YUM,DNF)管理Linux中的軟件包?Mar 17, 2025 pm 05:26 PM

文章討論了使用APT,YUM和DNF在Linux中管理軟件包,涵蓋安裝,更新和刪除。它比較了它們對不同分佈的功能和適用性。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
3 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。