我希望打印当前(本地)时间(基于std::chrono::system_clock
),同时包括毫秒,例如12:32:45.287
。我可以在没有毫秒的情况下完成,使用:
std::time_t time = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
char buffer[sizeof("HH:MM:SS")];
if (std::strftime(buffer, sizeof(buffer), "%H:%M:%S", std::localtime(&time)) == 0)
std::cout << "Error formating time" << std::endl;
else std::cout << buffer << std::endl;
如果我能得到一个毫秒的整数也是很好的。(我可以用std::localtime(&time)->tm_sec
获得秒数)
EDIT我想要一个可移植的解决方案,但如果不可能,那就选择一个适用于Windows 10/Visual C++14.0/Intel Compiler 16.0 的解决方案
如果您使用linux或unix,您可以在该时间段之前获得毫秒。
#include <cstdio>
#include <iostream>
#include <sys/time.h>
using namespace std;
long getCurrentTime() {
struct timeval tv;
gettimeofday(&tv,NULL);
return tv.tv_sec * 1000 + tv.tv_usec / 1000;
}
int main() {
cout<<"milliseconds: "<<getCurrentTime()<<endl;
return 0;
}
如果你想在C中实现可移植性,那么看看可移植库在使用什么,即Apache APR…
https://apr.apache.org/docs/apr/2.0/group__apr__time.html
或者用C编写的应用程序,这些应用程序被移植到您想要的平台上,即Mysql、Lua、JVM