C Basic time. h simple idea extension, c Basic time. h idea

Source: Internet
Author: User
Tags sleep function

C Basic time. h simple idea extension, c Basic time. h idea

Preface-simple requirements for time

Code related to the time business. It basically belongs to the bottom layer of the framework. The changes involved are very small. When I used to participate in game R & D,

There are a lot of requirements in this regard, and various types of plans are being shelved. This demand is rarely met after the development of Internet services in the industry.

However, when encapsulating the basic library, it is necessary to use the api function in this regard.

First, let's take a look at the basic requirements of time library encapsulation.

0. Thread Security

1. Interchange of time strings and timestamps

2. Comparison of time... for example, whether or not the same day

3. millisecond-precision time String Support

Everything starts from a simple process. Based on the above requirements, let's start with the author's ideas.

Times. h

# Ifndef _ H_TIMES # define _ H_TIMES # include <time. h> # include <stdbool. h> /// 1 s = 1000 ms = 000000us = 000000000ns // 1 second 1000 milliseconds 1000000 microseconds 1000000000 nanoseconds //~ Strive for the minimum time business unit ~ // # Ifdef _ GUNC __# include <unistd. h> # include <sys/time. h> /// msleep-sleep function. The granularity is millisecond. // m: milliseconds to sleep // return: void // inline void msleep (int MS) {usleep (MS * 1000 );} # endif # ifdef _ MSC_VER # include <windows. h> inline void msleep (int MS) {Sleep (MS);} // localtime_r-safe get current time struct // timep: input timestamp pointer // result: return Output Time Structure // return: Failed NULL, normal return result // inline struct tm * localtime_r (const time_t * timep , Struct tm * result) {return localtime_s (result, timep )? NULL: result ;}# endif // times_t-time string type # define INT_TIMES (64) typedef char times_t [INT_TIMES]; # endif/_ H_TIMES

We use localtime_r to solve the thread security problem of time_t acquisition.

In fact, the design of winds localtime_s is better than that of localtime_r.

            _Check_return_wat_            static __inline errno_t __CRTDECL localtime_s(                _Out_ struct tm*    const _Tm,                _In_  time_t const* const _Time                )            {                return _localtime64_s(_Tm, _Time);            }

Errno_t is obviously more accurate than struct tm * in semantic judgment, but from the perspective of time_t implementation, it is better to design interfaces like this.

errno_t localtime_s(time_t t, struct tm * result);

After all, the time_t input structure is sufficient.0th thread security requirementsIt's done.

Haha, looking at _ GUNC _ MSC_VER, I suddenly want to laugh. In the future, we may introduce _ clang _. Programmers = similar players.

 

Text-time simple ideas

  1. Interchange of time strings and timestampsFrom the perspective of function implementation, you can divide it into two parts.

I) Time string parse-> struct tm

Ii) struct tm-> time_t

First look at step I

// Times_tm-extract the bool times_tm (times_t tsr, struct tm * pm) from the time string {int c, num, * es, * py; if ((! Tsr) |! (C = * tsr) | c <'0' | c> '9') return false; num = 0; es = & pm-> tm_sec; py = & pm-> tm_year; do {if (c> = '0' & c <= '9') {num = 10 * num + c-'0 '; c = * ++ tsr; continue;} * py -- = num; if (py <es) break; // remove special characters and start for (;) again (;;) {if (c = * ++ tsr) = '\ 0') return false; if (c> = '0' & c <= '9 ') break;} num = 0;} while (c); // true: py <es | c = '\ 0' & py = es if (py <es) return true; if (py = es) {* es = num; return true;} return false ;}

This function can process the following types of time strings and return simple results.

"March 11, 2018"

"19:35:58"

"March 2018"

.........

Later, Step ii struct tm-> time_t

/// Time_get-resolution time string, return timestamp // tsr: Time string content // return: <0 is error // inline time_t time_get (times_t tsr) {struct tm m; // parse the if (! Times_tm (tsr, & m) return-1; // get the timestamp. If it fails, false m is returned. tm_mon-= 1; m. tm_year-= 1900; return mktime (& m );}

I wonder why there are magic numbers, 1 1900. (Note 0,-1 is the default magic number in api design)

This mainly follows the underlying design style of the compiler c runtime.

//-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+//// Types////-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+struct tm{    int tm_sec;   // seconds after the minute - [0, 60] including leap second    int tm_min;   // minutes after the hour - [0, 59]    int tm_hour;  // hours since midnight - [0, 23]    int tm_mday;  // day of the month - [1, 31]    int tm_mon;   // months since January - [0, 11]    int tm_year;  // years since 1900    int tm_wday;  // days since Sunday - [0, 6]    int tm_yday;  // days since January 1 - [0, 365]    int tm_isdst; // daylight savings time flag};

There are so many numbers. To put it bluntly, let's look at the numbers that have something to do with mathematics. A macro may not understand. There is a principle to write code here.

Write the code at the bottom layer.

In social life, how do the boss get it, how do we get it? He shot us and shot it... (ps: sb philosophy)

2. Comparison of time... for example, whether or not the same day

This implementation involves the time zone. Here I only implement the China section.

/// Time_day-determine whether the timestamp is the same day // n: The first timestamp // t: The second timestamp // return: true indicates the same day // inline bool time_day (time_t n, time_t t) {// China local applies, get the current day // GMT [World] + 8*3600 = CST [China] n = (n + 8UL * 3600)/(24*3600 ); t = (t + 8UL * 3600)/(24*3600); return n = t ;}

In the internationalization idea, you can use Configure.

Wrap a syntactic sugar function for the above function as follows:

/// Time_now-determine whether the timestamp is today // t: The timestamp to be determined // return: returns the current timestamp, -1 is error // inline time_t time_now (time_t t) {time_t n = time (NULL); return time_day (n, t )? N:-1 ;}

Or you can use the time string for comparison.

/// Times_day-determine whether the time string is the same day // ns: First Time string // ts: Second time string // return: true indicates the same day // bool times_day (times_t ns, times_t ts) {time_t t, n = time_get (ns); // if (n <0) | (t = time_get (ts) <0) return false; return time_day (n, t );}

More related judgment services, that is, building blocks. You can play with them by yourself.

  3. millisecond-precision time String Support

Here I encapsulate it like this. First, let's look at the Declaration.

/// Times_fmt-concatenate a string in fmt Format // fmt: it must contain % 04d % 02d % 02d % 02d % 02d % 02d % 02d % 03ld // buf: the final saved content // sz: buf length // return: the length of the generated string // int times_fmt (const char * fmt, char buf [], size_t sz ); /// times_str-get the millisecond string [22:38:34 500] // osr: return the generated string // return: returns the length of the generated string // # define STR_TIMES "% 04d-% 02d-% 02d % 02d: % 02d: % 02d % 03ld" inline int times_str (times_t osr) {return times_fmt (STR_TIMES, osr, sizeof (times_t ));}

Followed by the implementation Part

int times_fmt(const char * fmt, char buf[], size_t sz) {    struct tm m;    struct timespec s;    timespec_get(&s, TIME_UTC);    localtime_r(&s.tv_sec, &m);    return snprintf(buf, sz, fmt,                    m.tm_year + 1900, m.tm_mon + 1, m.tm_mday,                    m.tm_hour, m.tm_min, m.tm_sec,                     s.tv_nsec / 1000000);}

Straightforward thinking. Fill the meaning of each field in struct tm. Use timespec_get to get the time precision at the nanosecond level.

Times_str is frequently used in log library encapsulation.

Is it very easy? More packages can be extended in the Link Interface Design

Times. h https://github.com/wangzhione/structc/blob/master/structc/system/times.h

 

Started from time and stars ~ Maybe those are really random :)

 

Postscript-time is purely nonsense

Bugs must exist, and we hope they will all be improved in the modification process ~

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.