1.获取以秒为单位的时间戳
1.1 C++风格
#include <iostream>
#include <ctime>
int main()
{
std::time_t t = std::time(0); // t is an integer type
std::cout << t << " seconds since 01-Jan-1970\n";
return 0;
}
1.2 C风格
#include <iostream>
#include <sys/time.h>
int main()
{
unsigned long int sec1 = time(NULL);
time_t sec2 = time(NULL); // 这里的time_t不是std:time_t
std::cout << sec1 << std::endl;
std::cout << sec2 << std::endl;
return 0;
}
2.获取以毫秒为单位的时间戳
2.1 C++风格
#include <iostream>
#include <chrono>
int main()
{
std::chrono::milliseconds ms = std::chrono::duration_cast< std::chrono::milliseconds >(
std::chrono::system_clock::now().time_since_epoch()
);
std::cout << ms.count() << std::endl;
return 0;
}
2.2 C风格
#include <iostream>
#include <sys/time.h>
int main()
{
struct timeval tp;
gettimeofday(&tp, NULL);
long int ms = tp.tv_sec * 1000 + tp.tv_usec / 1000;
std:: cout << ms << std::endl;
return 0;
}