2

HI how to print time in macro second also with the use of following function in c++, I am using,

time_t rawtime;
time(&rawtime);
std::cout<<"Cuuent TIme is ::  "<< ctime(&rawtime)<< std::endl;

Above code will give me only hours, minutes and second. I also need the micro seconds. Any suggestion how to get time with micro seconds also?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
BSalunke
  • 11,499
  • 8
  • 34
  • 68
  • possible duplicate of [Get a timestamp in C in microseconds?](http://stackoverflow.com/questions/5833094/get-a-timestamp-in-c-in-microseconds) – Nim Sep 28 '11 at 09:47
  • There are so many duplicates - the one above is an example.. – Nim Sep 28 '11 at 09:47

3 Answers3

2

I used following code to get time in H,M,S,mS:

 char timeBuf  [256]; 
 struct timeval tv;
 struct timezone tz;
 struct tm *tm;
 gettimeofday(&tv, &tz);
 tm=localtime(&tv.tv_sec);
 sprintf (timeBuf, "%02d:%02d:%02d:%03ld",tm->tm_hour, tm->tm_min, tm->tm_sec, (tv.tv_usec/1000) );
CrazyC
  • 1,840
  • 6
  • 39
  • 60
1

BSalunke, look at this piece of code. Includes the uSeconds and the time_t structure you were using.

#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main( int argc, char **argv )
{
        struct timeval timeValue;
        long uSeconds;

        if ( gettimeofday( &timeValue, NULL ) == 0 )
        {
                // This is what you have:
                time_t time = timeValue.tv_sec;
                // This is what you are looking for:
                printf( "Current milliseconds: %ld\n", timeValue.tv_usec );
                return EXIT_SUCCESS;
        }
        else
                return EXIT_FAILURE;
}
0

Two options:

  1. gettimeofday()
  2. clock(...)
Nim
  • 33,299
  • 2
  • 62
  • 101
  • but can i get the time with hours, minits, second and also microseconds? with the use of above my code? – BSalunke Sep 28 '11 at 09:50
  • 1
    @BSalunke, I provided the methods you need to look at, and duplicate questions where this material is covered, you need to read the documentation - and yes it's possible. – Nim Sep 28 '11 at 09:59