C語言獲取Linux系統(tǒng)精確時間的方法
更新時間:2017年09月04日 14:25:28 作者:Yueers
下面小編就為大家?guī)硪黄狢語言獲取Linux系統(tǒng)精確時間的方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
gettimeofday()函數(shù)的使用方法
1.函數(shù)原型
#include <sys/time.h> int gettimeofday(struct timeval *tv, struct timezone *tz);
2.說明
gettimeofday()會把目前的時間用tv 結(jié)構(gòu)體返回,當?shù)貢r區(qū)的信息則放到tz所指的結(jié)構(gòu)中
3.結(jié)構(gòu)體
struct timeval{
long tv_sec;/*秒*/
long tv_usec;/*微妙*/
};
struct timezone{
int tz_minuteswest; /*和greenwich 時間差了多少分鐘*/
int tz_dsttime; /*DST的校正*/
}
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include <string.h>
#define SIZE_OF_DATETIME 20
void sysUsecTime(char *pTime)
{
struct timeval tv;
struct timezone tz;
int i=0;
struct tm *p;
char sys_time[SIZE_OF_DATETIME+1]="";
gettimeofday(&tv, &tz);
p = localtime(&tv.tv_sec);
sprintf(sys_time,"%d%d%d%d%d%d%ld",1900+p->tm_year, 1+p->tm_mon, p->tm_mday, p->tm_hour, p->tm_min, p->tm_sec, tv.tv_usec);
printf("strlen(sys_time)=[%d]\n",strlen(sys_time));
printf("sys_time=[%s]\n",sys_time);
/* 時間最大長度為: 年 4位、 月 2位 、日 2位 、時 2位 、分 2位 、秒 2位 毫秒 6位 = 20位 */
/* 對不夠長度的末尾補0 */
for ( i=strlen(sys_time);i<SIZE_OF_DATETIME;i++)
{
sys_time[i]='0';
}
sys_time[SIZE_OF_DATETIME]='\0';
strcpy(pTime,sys_time);
}
int main(void)
{
char strusecTime[SIZE_OF_DATETIME+1];
sysUsecTime(strusecTime);
printf("%s\n",strusecTime);
return 0;
}
以上這篇C語言獲取Linux系統(tǒng)精確時間的方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
C++實現(xiàn)LeetCode(200.島嶼的數(shù)量)
這篇文章主要介紹了C++實現(xiàn)LeetCode(200.島嶼的數(shù)量),本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下2021-07-07
c語言中的局部跳轉(zhuǎn)及全局跳轉(zhuǎn)功能
本文介紹了C語言中的goto語句,以及如何使用setjmp和longjmp實現(xiàn)跨函數(shù)的跳轉(zhuǎn),詳細講解了setjmp和longjmp的使用方法和注意事項,以及使用這種全局跳轉(zhuǎn)后變量狀態(tài)的不確定性,感興趣的朋友一起看看吧2024-09-09

