jellad.tarek
jellad.tarek

Reputation: 133

How to Get system clock in microseconds in C++?

I am working on a project using Visual C++ /CLR in console mode. How can I get the system clock in microseconds ? I want to display hours:minutes:seconds:microseconds

The following program works well but is not compatible with other platforms:

#include <stdio.h>
#include <sys/time.h>
int main()
{
     struct timeval tv;
     struct timezone tz;
     struct tm *tm;
     gettimeofday(&tv, &tz);
     tm=localtime(&tv.tv_sec);
     printf(" %d:%02d:%02d %ld \n", tm->tm_hour, tm->tm_min,tm->tm_sec, tv.tv_usec);
     return 0;
}

Upvotes: 1

Views: 13139

Answers (2)

jellad.tarek
jellad.tarek

Reputation: 133

thank you Mr ereOn

I followed your instructions and i have wrote this code ==> it works 100 %

#include <iostream>
#include "boost/date_time/posix_time/posix_time.hpp" 

typedef boost::posix_time::ptime Time;


int main (){

    int i;
    Time t1;

    for (int i=0;i<1000;i++)
    {

         t1=boost::posix_time::microsec_clock::local_time();
     std::cout << to_iso_extended_string(t1) << "\n";
    }


    return 0;
}

Upvotes: 0

ereOn
ereOn

Reputation: 55736

You could use ptime microsec_clock::local_time() from Boost.

The documentation is available here.

After that, you can use std::string to_iso_extended_string(ptime) to display the returned time as a string or you can use the members of ptime directly to format the output by yourself.

Anyway it is worth noting that:

Win32 systems often do not achieve microsecond resolution via this API. If higher resolution is critical to your application test your platform to see the achieved resolution.

So I guess it depends on how precise you require your "clock" to be.

Upvotes: 1

Related Questions