使用c ++ chrono打印当前系统时间(以纳秒为单位)

时间:2014-12-28 15:50:42

标签: c++ c++11

如何使用std::chrono库以下列格式打印当前时间?

格式为:hour:minute:second:millisecond:microsecond:nanosecond

1 个答案:

答案 0 :(得分:13)

<强> [编辑]

将代码更改为C ++样式:

#include <chrono>
#include <ctime>

std::chrono::time_point<std::chrono::system_clock> now = std::chrono::system_clock::now();
auto duration = now.time_since_epoch();

typedef std::chrono::duration<int, std::ratio_multiply<std::chrono::hours::period, std::ratio<8>
>::type> Days; /* UTC: +8:00 */

Days days = std::chrono::duration_cast<Days>(duration);
    duration -= days;
auto hours = std::chrono::duration_cast<std::chrono::hours>(duration);
    duration -= hours;
auto minutes = std::chrono::duration_cast<std::chrono::minutes>(duration);
    duration -= minutes;
auto seconds = std::chrono::duration_cast<std::chrono::seconds>(duration);
    duration -= seconds;
auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(duration);
    duration -= milliseconds;
auto microseconds = std::chrono::duration_cast<std::chrono::microseconds>(duration);
    duration -= microseconds;
auto nanoseconds = std::chrono::duration_cast<std::chrono::nanoseconds>(duration);

std::cout << hours.count() << ":"
          << minutes.count() << ":"
          << seconds.count() << ":"
          << milliseconds.count() << ":"
          << microseconds.count() << ":"
          << nanoseconds.count() << std::endl;

结果:

17:56:14:94:451:679

<强> [旧]

一个简单的例子:

#include <sys/time.h>

char fmt[64];
char buf[64];
struct timeval tv;
struct tm *tm;

gettimeofday (&tv, NULL);
tm = localtime (&tv.tv_sec);
strftime (fmt, sizeof (fmt), "%H:%M:%S:%%06u", tm);
snprintf (buf, sizeof (buf), fmt, tv.tv_usec);
printf ("%s\n", buf);

结果:

00:01:32:695240