Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing a time in milliseconds

The following piece of code is used to print the time in the logs:

#define PRINTTIME() struct tm  * tmptime;
time_t     tmpGetTime;
time(&tmpGetTime);
tmptime = localtime(&tmpGetTime);
cout << tmptime->tm_mday << "/" <<tmptime->tm_mon+1 << "/" << 1900+tmptime->tm_year << " " << tmptime->tm_hour << ":" << tmptime->tm_min << ":" << tmptime->tm_sec<<">>";

Is there any way to add milliseconds to this?

like image 214
ronan Avatar asked Jul 13 '09 16:07

ronan


People also ask

How do you find time in milliseconds?

To get the current time in milliseconds, you just need to convert the output of Sys. time to numeric, and multiply by 1000.


2 Answers

To have millisecond precision you have to use system calls specific to your OS.

In Linux you can use

#include <sys/time.h>

timeval tv;
gettimeofday(&tv, 0);
// then convert struct tv to your needed ms precision

timeval has microsecond precision.

In Windows you can use:

#include <Windows.h>

SYSTEMTIME st;
GetSystemTime(&st);
// then convert st to your precision needs

Of course you can use Boost to do that for you :)

like image 82
neuro Avatar answered Sep 18 '22 16:09

neuro


//C++11 Style:

cout << "Time in Milliseconds =" << 
 chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now().time_since_epoch()).count() 
 << std::endl;

cout << "Time in MicroSeconds=" << 
 chrono::duration_cast<chrono::microseconds>(chrono::steady_clock::now().time_since_epoch()).count() 
 << std::endl;
like image 22
user3762106 Avatar answered Sep 21 '22 16:09

user3762106