網站首頁 編程語言 正文
這兩個函數原型如下:
__CRT_INLINE time_t __cdecl mktime(struct tm *_Tm); __CRT_INLINE double __cdecl difftime(time_t _Time1,time_t _Time2);
mktime函數
mktime函數會把參數把?timeptr?所指向的結構轉換為自 1970 年 1 月 1 日以來持續時間的秒數,如果發生錯誤時則返回-1。
參數結構體原型如下:
struct tm { int tm_sec; /* 秒,范圍從 0 到 59 */ int tm_min; /* 分,范圍從 0 到 59 */ int tm_hour; /* 小時,范圍從 0 到 23 */ int tm_mday; /* 一月中的第幾天,范圍從 1 到 31 */ int tm_mon; /* 月份,范圍從 0 到 11 */ int tm_year; /* 自 1900 起的年數 */ int tm_wday; /* 一周中的第幾天,范圍從 0 到 6 */ int tm_yday; /* 一年中的第幾天,范圍從 0 到 365 */ int tm_isdst; /* 夏令時 */ };
下面直接通過一段代碼來演示。
#include <stdio.h> #include <stdlib.h> #include <time.h> int main(int argc, char** argv) { int ret,time_cnt; struct tm info; info.tm_year = 2022 - 1900; info.tm_mon = 1 - 1; info.tm_mday = 25; info.tm_hour = 11; info.tm_min = 28; info.tm_sec = 50; info.tm_isdst = -1; ret = mktime(&info); time_cnt = time(NULL); if( ret == -1 ) { printf("Error: unable to make time using mktime\n"); } else { printf("%d %d",ret,time_cnt); } return 0; }
首先定義時間結構體,然后給結構體中的變量賦值,將當前時間值賦給變量,然后在通過time函數獲取當前時間的秒數,最后將mktime函數轉換后的秒數和time函數返回的秒數打印出來。
通過結果可以看到兩個函數的秒數相差1,這是由于程序在編譯執行的時候延時了一秒,說明mktime函數轉換后的秒數和time函數返回的秒數是一樣的。
difftime函數
difftime函數有兩個時間參數,這個函數的主要作用返回這兩個時間就參數的差,也就是這兩個時間值相差的秒數。
一般可以通過這個函數來計算某段代碼運行的時間。
#include <stdio.h> #include <stdlib.h> #include <time.h> int main(int argc, char** argv) { time_t start_t, end_t; double diff_t; printf("程序啟動...\n"); time(&start_t); sleep(2); printf("運行結束!\n"); time(&end_t); diff_t = difftime(end_t, start_t); printf("\n開始時間: %d 結束時間: %d 代碼運行時間: %fs\n", start_t,end_t,diff_t); return 0; }
定義兩個變量來記錄程序運行前的時間值和程序運行后的時間值,然后通過延時函數來模擬程序的運行過程,最后通過difftime函數來計算函數運行的時長。
通過打印的結果可看出,延時函數的執行時間為2s,程序中的延時也是2s,說明函數計算的結果是正確的。在這里要注意一點difftime函數的返回值是double
類型的數據。
總結
原文鏈接:https://hxydj.blog.csdn.net/article/details/122961965
相關推薦
- 2022-03-23 C語言利用system調用系統命令行詳情_C 語言
- 2022-04-10 elasticsearch + spring boot 配置
- 2022-09-21 Python+pandas編寫命令行腳本操作excel的tips詳情_python
- 2022-02-13 QT 控件 QListWidget 設置所有事件都激發編輯(雙擊, 選擇, 選項變化)
- 2022-06-27 使用AOP+redis+lua做方法限流的實現_Redis
- 2022-06-19 C#文件非占用讀取與幫助類FileHelper_C#教程
- 2022-05-20 Python?文件處理之open()函數_python
- 2022-11-20 利用Go語言快速實現一個極簡任務調度系統_Golang
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支