C 學習 時間相關

2021-06-14 17:30:29 字數 1898 閱讀 7306

c++常用的函式在中(或time.h)

1,資料結構

表示時間的資料結構有三個:time_t , tm和timeval

time_t = long int, 用來表示絕對時間

tm是乙個struct,裡邊有如下成員:  tm_sec(秒), tm_min(分),tm_hour(小時),tm_mday(天/月),tm_mon(月),tm_year(年),tm_wday(星期),tm_yday(天/年),tm_isdst(夏時制)

timeval只有linux才有,定義在sys/time.h中, 優點是能精確到微秒, 也是乙個struct, 有兩個成員tv_sec和tv_usec

還有乙個clock_t,其實跟time_t一樣 是個長整形

2,常用函式:

time()定義: time_t time (time_t* timer);獲取絕對時間, 引數為空返回當前時間,不為空更新引數為當前時間, 常見的用法:

time_t  t=time(null);   

或:time(&t)

clock()獲取cpu時間, 具體原理不很懂~  與time()的區別在於不計入sleep的時間, 另外它的計量單位是微秒,意味著更加準確

gettimeofday()定義:int gettimeofday(struct timeval

*tv, struct timezone *tz);

這個是只有linux才有的(include sys/time.h),tz一般不用,好處是timeval可以精確到微秒,可以看做是乙個精確版的time(), 當然也沒有time方便

功能函式:

difftime():double difftime (time_t end, time_t beginning);

很好用的函式,注意第乙個引數是end,第二個才是start, 否則會返回乙個負值

轉換函式: 幾個資料結構和字串之間的互轉

互**time_t--> tm:localtime

struct tm * localtime (const time_t * timer);

tm-->time_t:mktime

time_t mktime (struct tm * timeptr);

轉成字串:

這兩個函式的坑爹之處在於後面自帶了乙個\n,導致非常不好用. 是作者yy了使用者想法結果弄巧成拙的典型範例, 所以寫程式(尤其是基礎庫)最好只提供基礎的,必需的服務,擴充套件之類的東西放到更高更接近應用的層面去做

tm格式:

asctime

char* asctime (const struct tm * timeptr);

time_t格式:

ctime

char* ctime (const time_t * timer)

好在有辦法補救:還有乙個格式化字串的函式strftime

size_t strftime (char* ptr, size_t maxsize, const char* format,

const struct tm* timeptr );

ptr是字串指標,

maxsize是字串最大長度,防止越界(其實我覺得沒有更好)

format是格式化字元,常用的格式:%s,%m.%h:秒,分,時%d, %m, %y:日,月,年

timeptr是tm格式的時間

返回字串長度(不溢位)或0(溢位)

注:現在各個時間函式已經都包括在iostream中,並成為名字空間std的一員. 例如 std::time_t

c 時間相關學習 time h

time.h coordinated universal time utc 協調世界時,又稱為世界標準時間,也就是大家所熟知的格林威治標準時間 greenwich mean time,gmt 比如,中國內地的時間與utc的時差為 8,也就是utc 8。美國是utc 5。calendar time 日...

C 時間轉換相關

system.datetime currenttime new system.datetime 取當前年月日時分秒 currenttime system.datetime.now 取當前年 int curyear currenttime.year 取當前月 int curmon currenttim...

C 時間戳 時間相關函式

時間戳 unix時間戳 unix timestamp 或稱unix時間 unix time posix時間 posix time 是一種時間表示方式,定義為從格林威治時間1970年01月01日00時00分00秒起至現在的總秒數 1.函式模型 return the current time and p...