linux常用的時間獲取函數(time,gettimeofday,clock_gettime,_ftime,localtime,strftime )


 

time()提供了秒級的精確度  
  
1、頭文件 <time.h>  
2、函數原型  
time_t time(time_t * timer)   
函數返回從TC1970-1-1 0:0:0開始到現在的秒數  
  
用time()函數結合其他函數(如:localtime、gmtime、asctime、ctime)可以獲得當前系統時間或是標准時間。  
 
#include <time.h>  
#include <stdio.h>  
int main(void)  
{  
    time_t t;   
    t = time(NULL);  
    printf("The number of seconds since January 1, 1970 is %ld",t);  
      
    return 0;  
}   
 
#include <stdio.h>  
#include <stddef.h>  
#include <time.h>  
int main(void)  
{  
    time_t timer;//time_t就是long int 類型  
    struct tm *tblock;  
    timer = time(NULL);//這一句也可以改成time(&timer);  
    tblock = localtime(&timer);  
    printf("Local time is: %s/n",asctime(tblock));  
      
    return 0;  
} 

 

 

 


gettimeofday()提供了微秒級的精確度  
  
1、頭文件 <time.h>  
2、函數原型  
int gettimeofday(struct timeval *tv, struct timezone *tz);   
  
gettimeofday()會把目前的時間由tv所指的結構返回,當地時區的信息則放到tz所指的結構中(可用NULL)。  
參數說明:  
    timeval結構定義為:  
    struct timeval  
    {  
        long tv_sec; /*秒*/  
        long tv_usec; /*微秒*/  
    };  
    timezone 結構定義為:  
    struct timezone  
    {  
        int tz_minuteswest; /*和Greenwich 時間差了多少分鍾*/  
        int tz_dsttime; /*日光節約時間的狀態*/  
    };  
    上述兩個結構都定義在/usr/include/sys/time.h。tz_dsttime 所代表的狀態如下  
        DST_NONE /*不使用*/  
        DST_USA /*美國*/  
        DST_AUST /*澳洲*/  
        DST_WET /*西歐*/  
        DST_MET /*中歐*/  
        DST_EET /*東歐*/  
        DST_CAN /*加拿大*/  
        DST_GB /*大不列顛*/  
        DST_RUM /*羅馬尼亞*/  
        DST_TUR /*土耳其*/  
        DST_AUSTALT /*澳洲(1986年以后)*/  
   
返回值: 成功則返回0,失敗返回-1,錯誤代碼存於errno。附加說明EFAULT指針tv和tz所指的內存空間超出存取權限。  
 
#include<stdio.h>  
#include<time.h>  
int main(void)  
{  
    struct timeval tv;  
    struct timezone tz;  
      
    gettimeofday (&tv , &tz);  
      
    printf(“tv_sec; %d/n”, tv,.tv_sec) ;  
    printf(“tv_usec; %d/n”,tv.tv_usec);  
      
    printf(“tz_minuteswest; %d/n”, tz.tz_minuteswest);  
    printf(“tz_dsttime, %d/n”,tz.tz_dsttime);  
      
    return 0;  
} 

 

 

clock_gettime( ) 提供了納秒級的精確度  
  
1、頭文件 <time.h>  
2、編譯&鏈接。在編譯鏈接時需加上 -lrt ;因為在librt中實現了clock_gettime函數  
3、函數原型  
int clock_gettime(clockid_t clk_id, struct timespect *tp);  
    參數說明:  
    clockid_t clk_id 用於指定計時時鍾的類型,有以下4種:  
        CLOCK_REALTIME:系統實時時間,隨系統實時時間改變而改變,即從UTC1970-1-1 0:0:0開始計時,中間時刻如果系統時間被用戶該成其他,則對應的時間相應改變  
        CLOCK_MONOTONIC:從系統啟動這一刻起開始計時,不受系統時間被用戶改變的影響  
        CLOCK_PROCESS_CPUTIME_ID:本進程到當前代碼系統CPU花費的時間  
        CLOCK_THREAD_CPUTIME_ID:本線程到當前代碼系統CPU花費的時間  
    struct timespect *tp用來存儲當前的時間,其結構如下:  
        struct timespec  
        {  
            time_t tv_sec; /* seconds */  
            long tv_nsec; /* nanoseconds */  
        };  
    返回值。0成功,-1失敗  
 
#include<stdio.h>  
#include<time.h>  
int main()  
{  
    struct timespec ts;  
      
    clock_gettime(CLOCK_REALTIME, &ts);  
    printf("CLOCK_REALTIME: %d, %d", ts.tv_sec, ts.tv_nsec);  
      
    clock_gettime(CLOCK_MONOTONIC, &ts);//打印出來的時間跟 cat /proc/uptime 第一個參數一樣  
    printf("CLOCK_MONOTONIC: %d, %d", ts.tv_sec, ts.tv_nsec);  
      
    clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts);  
    printf("CLOCK_PROCESS_CPUTIME_ID: %d, %d", ts.tv_sec, ts.tv_nsec);  
      
    clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts);  
    printf("CLOCK_THREAD_CPUTIME_ID: %d, %d", ts.tv_sec, ts.tv_nsec);  
      
    printf("/n%d/n", time(NULL));  
  
    return 0;  
}  
/proc/uptime里面的兩個數字分別表示:   
the uptime of the system (seconds), and the amount of time spent in idle process (seconds).   
把第一個數讀出來,那就是從系統啟動至今的時間,單位是秒  
 

 

 

_ftime()提供毫秒級的精確度  
  
1、頭文件 <sys/types.h> and <sys/timeb.h>   
2、函數原型  
void _ftime(struct _timeb *timeptr);   
參數說明:  
    struct _timeb   
    {  
        time_t time;  
        unsigned short millitm;  
        short timezone;  
        short dstflag;  
    };   
 
#include <stdio.h>  
#include <sys/timeb.h>  
#include <time.h>  
  
void main( void )  
{  
    struct _timeb timebuffer;  
    char *timeline;  
  
    _ftime( &timebuffer );  
    timeline = ctime( & ( timebuffer.time ) );  
  
    printf( "The time is %.19s.%hu %s", timeline, timebuffer.millitm, &timeline[20] );  
}  

 

 
頭文件:#include <time.h>

定義函數:struct tm *localtime(const time_t * timep);

函數說明:localtime()將參數timep 所指的time_t 結構中的信息轉換成真實世界所使用的時間日期表示方法,然后將結果由結構tm 返回。結構tm 的定義請參考gmtime()。此函數返回的時間日期已經轉換成當地時區。

返回值:返回結構tm 代表目前的當地時間。

范例
#include <time.h>
main(){
    char *wday[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
    time_t timep;
    struct tm *p;
    time(&timep);
    p = localtime(&timep); //取得當地時間
    printf ("%d%d%d ", (1900+p->tm_year), (l+p->tm_mon), p->tm_mday);
    printf("%s%d:%d:%d\n", wday[p->tm_wday], p->tm_hour, p->tm_min, p->tm_sec);
}

執行結果:
2000/10/28 Sat 11:12:22

 

 

size_t strftime ( char * ptr, size_t maxsize, const char * format, const struct tm * timeptr );

Format time to string
Copies into  ptr  the content of  format , expanding its format tags into the corresponding values as specified by timeptr , with a limit of  maxsize  characters.

Parameters

ptr
Pointer to the destination array where the resulting C string is copied.
maxsize
Maximum number of characters to be copied to  ptr.
format
C string containing any combination of regular characters and special format specifiers. These format specifiers are replaced by the function to the corresponding values to represent the time specified in  timeptr. They all begin with a percentage ( %) sign, and are:
specifier Replaced by Example
%a Abbreviated weekday name * Thu
%A Full weekday name * Thursday
%b Abbreviated month name * Aug
%B Full month name * August
%c Date and time representation * Thu Aug 23 14:55:02 2001
%d Day of the month (01-31) 23
%H Hour in 24h format (00-23) 14
%I Hour in 12h format (01-12) 02
%j Day of the year (001-366) 235
%m Month as a decimal number (01-12) 08
%M Minute (00-59) 55
%p AM or PM designation PM
%S Second (00-61) 02
%U Week number with the first Sunday as the first day of week one (00-53) 33
%w Weekday as a decimal number with Sunday as 0 (0-6) 4
%W Week number with the first Monday as the first day of week one (00-53) 34
%x Date representation * 08/23/01
%X Time representation * 14:55:02
%y Year, last two digits (00-99) 01
%Y Year 2001
%Z Timezone name or abbreviation CDT
%% % sign %
* The specifiers whose description is marked with an asterisk (*) are locale-dependent.
timeptr
Pointer to a  tm structure that contains a calendar time broken down into its components (see  tm).

Return Value

If the resulting C string fits in less than  maxsize  characters including the terminating null-character, the total number of characters copied to  ptr  (not including the terminating null-character) is returned.
Otherwise, zero is returned and the contents of the array are indeterminate.

Portability

This description corresponds to the C++ version of this function (which is the same as in the ISO-C Standard of 1990). C compilers may support additional specifiers and modifiers for the  format  parameter of this function, which are not described here.

Example

/*  strftime example  */
#include <stdio.h>
#include <time.h>

int main ()
{
  time_t rawtime;
   struct tm * timeinfo;
   char buffer [ 80];

  time ( &rawtime );
  timeinfo = localtime ( &rawtime );

  strftime (buffer, 80, " Now it's %I:%M%p. ",timeinfo);
  puts (buffer);
  
   return  0;
}

Example output:
 Now it's 03:21PM. 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM