1

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;
}
Coding Mash
  • 3,338
  • 5
  • 24
  • 45
jellad.tarek
  • 135
  • 1
  • 3
  • 10

2 Answers2

1

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.

ereOn
  • 53,676
  • 39
  • 161
  • 238
0

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;
}
jellad.tarek
  • 135
  • 1
  • 3
  • 10
  • 5
    This is not how SO works. You should _accept_ ereOn's answer, and -- if you feel a complete code listing is necessary -- _edit_ ereOn's post or use the comment function to ask ereOn to add code. – jogojapan May 06 '12 at 01:24