C++ 获取当前时间的两种方法(精确到毫秒)
2022-11-24 22:36:21
michael007js
1684
1. boost 方法
#include <boost/date_time/posix_time/posix_time.hpp>
std::string now_str1()
{
// Get current time from the clock, using microseconds resolution
const boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time();
// Get the time offset in current day
const boost::posix_time::time_duration td = now.time_of_day();
//
// Extract hours, minutes, seconds and milliseconds.
//
// Since there is no direct accessor ".milliseconds()",
// milliseconds are computed _by difference_ between total milliseconds
// (for which there is an accessor), and the hours/minutes/seconds
// values previously fetched.
//
const long hours= td.hours();
const long minutes= td.minutes();
const long seconds= td.seconds();
const long milliseconds = td.total_milliseconds() - (hours * 3600 + minutes * 60 + seconds) * 1000;
char buf[40];
sprintf(buf, "%02ld:%02ld:%02ld.%03ld",hours, minutes, seconds, milliseconds);
return buf;
}
2. 标准库方法
#include <sys/time.h>
using namespace std;
std::string now_str2()
{
struct timeval tpend;
gettimeofday(&tpend,NULL);
int secofday = (tpend.tv_sec + 3600 * 8 ) % 86400;
int hours = secofday / 3600; int minutes = (secofday - hours * 3600 ) / 60; int seconds = secofday % 60; int milliseconds = tpend.tv_usec/1000; char buf[40];
sprintf(buf, "%02ld:%02ld:%02ld.%03ld", hours, minutes, seconds, milliseconds);
return buf;
}
3. chrono
#include <chrono> using namespace std::chrono; time_point<high_resolution_clock> t1 = std::chrono::system_clock::now(); QThread::usleep(5432); time_point<high_resolution_clock> t2 = std::chrono:: system_clock::now(); cout << "tick count = " << (t2-t1).count() <<endl; //微秒 int64_t elapsed_micro() const { return duration_cast<chrono::microseconds>(high_resolution_clock::now() - m_begin).count(); }