string getNowSysTime(string &outPut) { char szBuf[256] = {0}; struct timeval tv; struct timezone tz; struct tm *p; gettimeofday(&tv, &tz); p = localtime(&tv.tv_sec); snprintf(szBuf, 256, "%02d-%02d-%02d %02d:%02d:%02d", p->tm_year + 1900, p->tm_mon + 1, p->tm_mday, p->tm_hour, p->tm_min, p->tm_sec); return outPut = szBuf; } string GetSysUsecTimeHMS() { char szBuf[256] = {0}; struct timeval tv; struct timezone tz; struct tm *p; gettimeofday(&tv, &tz); p = localtime(&tv.tv_sec); snprintf(szBuf, 256, "%02d-%02d-%02d %02d:%02d:%02d.%06ld", p->tm_year + 1900, p->tm_mon + 1, p->tm_mday, p->tm_hour, p->tm_min, p->tm_sec, tv.tv_usec); return szBuf; }
gettimeofday是計算機函數,使用C語言編寫程序需要獲得當前精確時間(1970年1月1日到現在的時間),或者為執行計時,可以使用gettimeofday()函數。
#include <sys/time.h>
int gettimeofday(struct
timeval*tv, struct timezone *tz);
其參數tv是保存獲取時間結果的結構體,參數tz用於保存時區結果:
struct timezone{
int tz_minuteswest;/*格林威治時間往西方的時差*/
int tz_dsttime;/*DST 時間的修正方式*/
}
timezone 參數若不使用則傳入NULL即可。
而結構體timeval的定義為:
struct timeval{
long int tv_sec; // 秒數
long int tv_usec; // 微秒數
}
它獲得的時間精確到微秒(1e-6 s)量級。在一段代碼前后分別使用gettimeofday可以計算代碼執行時間:
struct timeval tv_begin, tv_end;
gettimeofday(&tv_begin, NULL);
foo();
gettimeofday(&tv_end, NULL);
函數執行成功后返回0,失敗后返回-1,錯誤代碼存於errno中。