C++ 11打印当前系统时间(包括毫秒)
问题描述:
我希望打印当前(本地)时间(基于说std::chrono::system_clock
),同时包括毫秒(例如,毫秒)。 12:32:45.287
。 我可以不用毫秒,具有:C++ 11打印当前系统时间(包括毫秒)
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
)
编辑我想一个便携式解决方案,但如果这是不可能的,比一个适用于Windows 10 /的Visual C++ 14.0 /英特尔编译器16.0
答
你可以得到如果您使用linux或unix,则此时间间隔为毫秒。用C语言编写
#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
或应用被移植到平台,你想目标即Mysql,Lua,JVM
对不起,我的系统没有'sys/time.h'头文件 – Isaac
您是否使用Windows? – Philokey
是的(Windows 10/Visual C++ 14/Intel编译器16.0) – Isaac