如何使用ctime()函数在微秒内打印时间?

时间:2011-09-28 09:41:21

标签: c++ linux

如何在c ++中使用以下函数,如何在宏中打印时间,我正在使用,

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

上面的代码只会给我几小时,几分钟和几秒钟。我还需要微秒。 任何建议如何获得微秒的时间呢?

3 个答案:

答案 0 :(得分:2)

我使用以下代码来获取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) );

答案 1 :(得分:1)

BSalunke,看看这段代码。包括您正在使用的uSeconds和time_t结构。

#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;
}

答案 2 :(得分:0)

两个选项:

  1. gettimeofday()
  2. clock(...)