【问题标题】:how to print time in micro seconds using ctime() function?如何使用 ctime() 函数以微秒为单位打印时间?
【发布时间】:2011-11-26 17:30:45
【问题描述】:

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

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

上面的代码只会给我几小时、几分钟和几秒钟。我也需要微秒。 有什么建议如何用微秒获得时间吗?

【问题讨论】:

标签: c++ linux


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      两种选择:

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

      【讨论】:

      • 但是我可以得到小时、分钟、秒和微秒的时间吗?使用上面我的代码?
      • @BSalunke,我提供了您需要查看的方法,并且在涉及此材料的地方重复了问题,您需要阅读文档 - 是的,这是可能的。
      猜你喜欢
      • 2013-03-22
      • 1970-01-01
      • 1970-01-01
      • 2014-06-24
      • 2012-01-12
      • 2016-02-14
      • 2021-05-16
      • 1970-01-01
      相关资源
      最近更新 更多