#include <sys/time.h><br />#include <time.h><br />#include <stdio.h><br />#include <iostream><br />#include <string.h><br />using namespace std;<br />double difftimeval(const struct timeval *tv1, const struct timeval *tv2)<br />{<br /> double d;<br /> time_t s;<br /> suseconds_t u;<br /> s = tv1->tv_sec - tv2->tv_sec;<br /> u = tv1->tv_usec - tv2->tv_usec;<br /> if (u < 0)<br /> --s;<br /> d = s;<br /> d *= 1000000.0;<br /> d += u;<br /> return d;<br />}<br />char* strftimeval(const struct timeval *tv, char *buf)<br />{<br /> struct tm tm;<br /> size_t len = 28;<br /> localtime_r(&tv->tv_sec, &tm);<br /> strftime(buf, len, "%Y-%m-%d %H:%M:%S", &tm);<br /> len = strlen(buf);<br /> sprintf(buf + len, ".%06.6d", (int)(tv->tv_usec));<br /> return buf;<br />}<br />char* getstimeval(char *buf)<br />{<br /> struct timeval tv;<br /> struct tm tm;<br /> size_t len = 28;<br /> gettimeofday(&tv, NULL);<br /> localtime_r(&tv.tv_sec, &tm);<br /> strftime(buf, len, "%Y-%m-%d %H:%M:%S", &tm);<br /> len = strlen(buf);<br /> sprintf(buf + len, ".%06.6d", (int)(tv.tv_usec));<br /> return buf;<br />}<br />//get system time<br />void SendCentreTime(char* sCurDate)<br />{<br />struct tm *current_date;<br /> time_t seconds;<br /> time(&seconds);<br /> current_date = localtime(&seconds);<br /> memset(sCurDate, 0 , sizeof(sCurDate));<br /> sprintf(sCurDate, "%04d%02d%02d%02d%02d%02d",<br /> current_date->tm_year+1900,<br /> current_date->tm_mon+1,<br /> current_date->tm_mday,<br /> current_date->tm_hour,<br /> current_date->tm_min,<br /> current_date->tm_sec);<br />}<br />long long GetMillSec()<br />{<br />long long nMillSec = 0; </p><p>struct timeval tv;<br />gettimeofday(&tv,NULL); </p><p>nMillSec = (long long)tv.tv_sec * 1000;<br />nMillSec += tv.tv_usec / 1000;</p><p>return nMillSec;<br />}<br />int main(int argc, char *argv[])<br />{<br /> char buf[28];<br /> char cDate[128] = {0};<br /> struct timeval tv1;<br /> struct timeval tv2;</p><p> long long tm = GetMillSec();<br />SendCentreTime(cDate);<br /> gettimeofday(&tv1, NULL);<br /> printf("%s/n", getstimeval(buf));<br /> gettimeofday(&tv2, NULL);<br /> printf("%s/n", strftimeval(&tv1, buf));<br /> printf("%s/n", strftimeval(&tv2, buf));<br /> printf("%f/n", difftimeval(&tv2, &tv1));<br /> return 0;<br />}<br />