C++11 提供了新的獲取系統時間的庫函數,在獲取時間的時候一般常用的是獲取time since epoch,下面來看一下如何獲取這個時間。
#include <iostream>
#include <chrono>
#include <ctime>
#include <sys/time.h>
#include <cstdint>
constexpr int microSecPerSec = 1000000;
int main()
{
std::chrono::time_point<std::chrono::system_clock> p1, p2, p3;
struct timeval tv;
int64_t mSecond;
p2 = std::chrono::system_clock::now();
p3 = p2 - std::chrono::hours(24);
gettimeofday(&tv,NULL);
mSecond = tv.tv_sec ;
std::time_t epoch_time = std::chrono::system_clock::to_time_t(p1); // seconds
std::cout << "epoch: " << std::ctime(&epoch_time);
std::time_t today_time = std::chrono::system_clock::to_time_t(p2);
std::cout << "today: " << std::ctime(&today_time);
std::cout << "hours since epoch: "
<< std::chrono::duration_cast<std::chrono::hours>( //hours
p2.time_since_epoch()).count()
<< std::endl;
std::cout << "yesterday, hours since epoch: "
<< std::chrono::duration_cast<std::chrono::hours>(
p3.time_since_epoch()).count()
<< std::endl;
std::cout << "Microseconds since epoch: (chrono) : " //microseconds
<< std::chrono::duration_cast<std::chrono::microseconds>(p2.time_since_epoch()).count() // p2 - p1 ==
<<std::endl;
std::cout << "Microseconds since epoch: (gettimeofday) :" << mSecond * microSecPerSec + tv.tv_usec
<<std::endl;
return 0;
}
結果:
C:\Users\zhuyp\Desktop\tmp>cpp_time
epoch: Thu Jan 01 08:00:00 1970
today: Fri Jan 24 23:51:10 2014
hours since epoch: 386271
yesterday, hours since epoch: 386247
Microseconds since epoch: (chrono) : 1390578670080869
Microseconds since epoch: (gettimeofday) :1390578670080869