文中代码主要来自
- http://stackoverflow.com/questions/6012663/get-unix-timestamp-with-c
- http://stackoverflow.com/questions/19555121/how-to-get-current-timestamp-in-milliseconds-since-1970-just-the-way-java-gets
- http://stackoverflow.com/questions/2831841/how-to-get-time-in-millis-in-c-just-like-java
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;
}
编译运行:
$ g++ -Wall test.cpp
$ ./a.out
1467214075 seconds since 01-Jan-1970
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;
}
编译运行:
$ g++ -Wall test.cpp
$ ./a.out
1467214468
1467214468
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;
}
编译运行:
$ g++ -std=c++11 -Wall test.cpp
$ ./a.out
1467215317714
std::chrono属于C++ 11.
相关:
- http://en.cppreference.com/w/cpp/chrono/duration
- http://www.cplusplus.com/reference/chrono/duration/
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;
}
编译运行:
$ g++ -Wall test.cpp
$ ./a.out
1467215481946