After doing quite a bit of C++ recently, I thought I would post my method for getting the current system time in milliseconds in C++ for both Mac OS X and Windows. The Mac version might translate to other Unix platforms, but you’ll have to check the docs or man pages.
Mac OS X
#include <sys/time.h> timeval time; gettimeofday(&time, NULL); long millis = (time.tv_sec * 1000) + (time.tv_usec / 1000);
This actually returns a struct that has microsecond precision.
Windows
#include "windows.h" SYSTEMTIME time; GetSystemTime(&time); WORD millis = (time.wSeconds * 1000) + time.wMilliseconds;
This code gives the milliseconds within the last minute. If you want milliseconds since epoch or some other fixed point in time it will require a bit more math on the SYSTEMTIME struct.
Can someone send a .cpp file, it won’t compile it says:
gcc /Users/Alexandre/Desktop/timeInMS.cpp -o ~/Desktop/Time
/usr/bin/ld: Undefined symbols:
___gxx_personality_v0
collect2: ld returned 1 exit status
Thank you!
LikeLike
Hi
I tried the program that you have written. But when I print ‘millis’ I get a negative value. How can I avoid it?
LikeLike
Shishir,
You might want to use printf( “%ld”, millis ) to avoid the negative values.
If you’re having trouble compiling this, try “struct timeval” instead of “timeval”.
LikeLike
After a long search i have find the good code for Windows VC++.
#include “windows.h”
SYSTEMTIME time;
GetSystemTime(&time);
WORD millis = (time.wSeconds * 1000) + time.wMilliseconds;
is working fine for getting the time in millisecond..
Good code
LikeLike
Hi,
I am student of BSCS.. I am trying to learn c and c++ nowadays. I am a beginner so i can’t understand much about this time get code from windows. If anyone please please help … How can i code it in struct.. And if anyone could provide me some material of c++ or c to learn it best. I will be very thankful to him/her…. thankyou . umar
LikeLike
Just one correction: It’s not “wSeconds” it’s “wSecond”.
In this line:
WORD millis = (time.wSeconds * 1000) + time.wMilliseconds;
Replace with:
WORD millis = (time.wSecond * 1000) + time.wMilliseconds;
LikeLike