linux5 擷取時間函數

來源:互聯網
上載者:User

#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 /> 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.