一、ftime是什麼?
ftime是一個C標準庫函數,用於獲取當前時間和日期。
#include <time.h> time_t time(time_t *t); struct tm *localtime(const time_t *t);
其中,time返回的是從1970年1月1日0時0分0秒至今的秒數,而localtime則將time返回的秒數轉換為一個結構體,結構體中包含了年、月、日、時、分、秒等時間信息。
二、獲取當前時間
要獲取當前時間,我們只需要調用time函數即可:
#include <stdio.h>
#include <time.h>
int main(){
time_t current_time;
time(¤t_time);
printf("Current time is: %s\n", ctime(¤t_time));
return 0;
}
運行結果:
Current time is: Tue Apr 20 14:28:56 2021
三、格式化輸出時間
ctime函數返回的時間格式並不是我們常見的日期時間格式,我們需要使用strftime函數將時間格式化為我們需要的格式。
#include <stdio.h>
#include <time.h>
int main(){
time_t current_time;
time(¤t_time);
char time_str[100];
strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", localtime(¤t_time));
printf("Current time is: %s\n", time_str);
return 0;
}
運行結果:
Current time is: 2021-04-20 14:28:56
四、計算時間差
有時我們需要計算兩個時間之間的差,可以通過將兩個時間轉為秒數,再相減得到時間差。
#include <stdio.h>
#include <time.h>
int main(){
time_t start_time, end_time;
double diff;
time(&start_time);
sleep(5);
time(&end_time);
diff = difftime(end_time, start_time);
printf("Time difference is: %.2lf seconds\n", diff);
return 0;
}
運行結果:
Time difference is: 5.00 seconds
五、設置定時器
我們可以使用定時器來定時執行某段代碼,可以使用alarm函數。
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
void alarm_handler(int signum){
printf("Alarm triggered!\n");
//重新設置定時器
alarm(3);
}
int main(){
//安裝信號處理器
signal(SIGALRM, alarm_handler);
//設置定時器
alarm(3);
//等待定時器信號觸發
while(1){
sleep(1);
}
return 0;
}
運行結果:
Alarm triggered! Alarm triggered! Alarm triggered! ...
六、總結
本文通過對ftime函數的介紹,詳細闡述了如何獲取當前時間和日期、格式化輸出時間、計算時間差和設置定時器等。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/253823.html
微信掃一掃
支付寶掃一掃