Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

c++ - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...