1

I wish to print the current (local) time (based on say std::chrono::system_clock) whilst including milliseconds, e.g. 12:32:45.287. I can do it without milliseconds, with:

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;

It would also be good if I could get an integer number of milliseconds. (I can get seconds with std::localtime(&time)->tm_sec)

EDIT I would like a portable solution, but if that's not possible, than one that works with Windows 10/Visual C++ 14.0/Intel Compiler 16.0

Isaac
  • 816
  • 5
  • 12

2 Answers2

0

You can get milliseconds by this timeval if you use linux or 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;
}
Philokey
  • 491
  • 2
  • 5
  • 14
0

If you want to do it portably in C then look at what the portable libraries are using ie Apache APR...

https://apr.apache.org/docs/apr/2.0/group__apr__time.html

Or applications written in C that are ported to the platforms you want to target ie Mysql, Lua, JVM

Harry
  • 11,298
  • 1
  • 29
  • 43