文中代碼主要來自java
#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; }
編譯運行:ios
$ g++ -Wall test.cpp $ ./a.out 1467214075 seconds since 01-Jan-1970
#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; }
編譯運行:c++
$ g++ -Wall test.cpp $ ./a.out 1467214468 1467214468
#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; }
編譯運行:unix
$ g++ -std=c++11 -Wall test.cpp $ ./a.out 1467215317714
std::chrono屬於C++ 11.c++11
相關:code
#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; }
編譯運行:get
$ g++ -Wall test.cpp $ ./a.out 1467215481946