c語言時間函數大全
1、time(time_t&)
#include <time.h>
time_t t
time (&t) //獲取1970年以來的秒數,此處是utc時間
time_t實際上為32位或者64位整數
2、localtime(time_t) 和 gmtime(time_t)
根據上面獲得的秒數t
struct tm * lt = localtime (&t) //轉換為本時區時間信息
struct tm * gt=gmtime (&t) //轉換為utc時間信息
其中:
struct tm {
int tm_sec //秒
int tm_min //分
int tm_hour //小時
int tm_mday //日
int tm_mon //月
int tm_year //年
int tm_wday //星期,其中0代表星期天,1代表星期一
int tm_yday //從每年的1月1日開始的天數 ,其中0代表1月1日
int tm_isdst //夏令時標識符
}
3、mktime(struct tm*)
t=mktime(lt) //將時間結構lt轉為1970年以來的秒數,也可以自己手工構建tm結構
此處lt為本時區時間信息
4、GetLocalTime(SYSTEMTIME&) 獲取本地時間,有毫秒
SetLocalTime(SYSTEMTIME&) 設置本地時間
SYSTEMTIME st
GetLocalTime(&st)
其中:
STRUCT SYSTEMTIME
{
WORD wYear 年
WORD wMonth 月
WORD wDayOfWeek 星期,0=星期日,1=星期一...
WORD wDay 日
WORD wHour 時
WORD wMinute 分
WORD wSecond 秒
WORD wMilliseconds 毫秒
}
GetSystemTime(SYSTEMTIME&)和SetSystemTime(SYSTEMTIME&) 操作的是UTC時間,其他相同。
5、void ftime(struct timeb *)
#include <sys/timeb.h>
獲取時間,有毫秒
struct timeb tp
ftime(&tp)
其中:
struct timeb{
time_t time /* 為1970-01-01至今的秒數*/
unsigned short millitm /* 毫秒 */
short timezone /* 時區差值,單位為分鐘 */
short dstflag /* 夏令時標識 */
}
6、獲取文件的時間信息
#include<sys/stat.h>
int stat(const char * file_name, struct stat *buf)
具體信息請自行搜索
7、clock()函數
返回從程序啟動到調用時刻的時間間隔。可用於測量兩個事件之前的時間:
clock_t start, finish
double duration
start = clock()
//...事件
finish = clock()
duration = (double)(finish - start) / CLOCKS_PER_SEC
printf( "%f secondsn", duration )
8、gettimeofday()
int gettimeofday(struct timeval*tv, struct timezone *tz)
struct timeval{
long int tv_sec // 1970年以來的秒數
long int tv_usec // 微秒數
}
可以計算代碼執行時間:
struct timeval tv_begin, tv_end
gettimeofday(&tv_begin, NULL)
//...
gettimeofday(&tv_end, NULL)
9、GetTickCount()
它返回從操作系統啟動到當前所經過的毫秒數,返回值以32位的雙字類型DWORD存儲,因此可以存儲的最大值是(2^32-1) ms約為49.71天,因此若系統運行時間超過49.71天時,這個數就會歸0。
10、GetSystemTimeAsFileTime(FILETIME *)
struct _FILETIME {
DWORDdwLowDateTime
DWORDdwHighDateTime
} FILETIME
相關函數:
SYSTEMTIME st
FILETIME ft
SystemTimeToFileTime(&st, &ft)
FileTimeToSystemTime(&ft, &st)
11、TimeGetTime
和GetTickCount差不多。GetTickCount精度15毫秒,TimeGetTime精度為1ms