Jan 052009

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

This actually returns a struct that has microsecond precision.


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.

  8 Responses to “Getting the current system time in milliseconds with C++”

  1. […] here:  Getting the current system time in milliseconds with C++ Share and […]

  2. 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:
    collect2: ld returned 1 exit status

    Thank you!

  3. Hi

    I tried the program that you have written. But when I print ‘millis’ I get a negative value. How can I avoid it?

  4. 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”.

  5. After a long search i have find the good code for Windows VC++.
    #include “windows.h”
    SYSTEMTIME time;
    WORD millis = (time.wSeconds * 1000) + time.wMilliseconds;
    is working fine for getting the time in millisecond..

    Good code

  6. […] ref:here Share this:TwitterFacebookLike this:LikeBe the first to like this. This entry was posted in Uncategorized by zahraee. Bookmark the permalink. […]

  7. 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

  8. 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;

 Leave a Reply



You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">