2011-09-28 84 views
2

HI如何打印時間在宏觀第二也與使用下面的C++函數的,我使用,如何使用ctime()函數在微秒內打印時間?

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

上面的代碼給我唯一的小時,分​​鍾和秒。我也需要微秒。 任何建議如何獲得微秒的時間呢?

+0

的[?獲取關於C中微秒時間戳(可能重複http://stackoverflow.com/questions/5833094/get-a-timestamp-in-c-in-microseconds) – Nim

+0

有這麼多的重複項 - 上面的是一個例子.. – Nim

回答

2

我用下面的代碼在H,M,S,微軟獲得時間:

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)); 
+0

謝謝@CrazyC。 – BSalunke

0

兩個選項:

  1. gettimeofday()
  2. clock(...)
+0

但我可以得到的時間與小時,minits,秒和微秒?使用上面我的代碼? – BSalunke

+1

@BSalunke,我提供了您需要查看的方法,並在涵蓋此資料的地方複製問題,您需要閱讀文檔 - 是的,這是可能的。 – Nim

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; 
} 
相關問題