linux的計時函數,用於獲取當前時間。
1. gettimeofday()
函數 | 結構體 | 精度 |
---|---|---|
time() | time_t | s |
gettimeofday() | struct timeval | us |
計時只使用gettimeofday()函數來獲取當前時間:
- time()函數精度太低,gettimeofday()函數以微秒為單位,可獲取us/ms/s的精度,足以滿足日常計時需要。
2. redis中的計時封裝函數
/*
* util_time.h
*
* Created on: 2018-6-4
* Author:
*/
#ifndef UTIL_TIME_H_
#define UTIL_TIME_H_
#include <sys/time.h>
/* Return the UNIX time in microseconds */
long long ustime(void) {
struct timeval tv;
long long ust;
gettimeofday(&tv, NULL);
ust = ((long long)tv.tv_sec)*1000000;
ust += tv.tv_usec;
return ust;
}
/* Return the UNIX time in milliseconds */
long long mstime(void) {
return ustime()/1000;
}
// #define UTIL_TIME_TEST
#ifdef UTIL_TIME_TEST
#include <unistd.h>
#include <iostream>
int main()
{
long long llStart = mstime();
sleep(2);
long long llEnd=mstime();
std::cout<<llEnd-llStart<<"ms"<<std::endl;
return 0;
}
#endif
#endif /* UTIL_TIME_H_ */
3. 時間戳和本地時間的轉換
#include <time.h>
#include <iostream>
using namespace std;
int main()
{
// __int64 時間戳 time(nullptr)
// 時間戳是從格林威治時間1970年01月01日00時00分00秒(北京時間1970年01月01日08時00分00秒)起至現在的總秒數。
// 現在時間戳的長度是十位(1435113975--2015/6/24 10:46:15)
time_t raw_time;
raw_time = time(nullptr);
cout << raw_time << endl; // 1515049816
// 時間戳到本地時間轉換 localtime(&raw_time), asctime(time_info) convert tm structure to string.
struct tm *time_info=nullptr;
time_info = localtime(&raw_time);
cout << asctime(time_info); // Thu Jan 04 15:10 : 16 2018
cout << time_info->tm_wday << endl; // 4 --> 周四
// 本地時間到時間戳轉換 mktime(time_info)
time_t after_time = mktime(time_info);
cout << after_time << endl; // 1515049816
return 0;
}