layout: post title: "title" subtitle: "time" date: 2019-04-22 15:52:12 author: "soaringsoul" header-img: "img/posts/default_post.jpg" catalog: true tags: - tag
sleep
ifdef _WIN32
#include <windows.h>
void sleep(unsigned milliseconds)
{
Sleep(milliseconds);
}
else
#include <unistd.h>
void sleep(unsigned milliseconds)
{
usleep(milliseconds * 1000); // takes microseconds
}
endif
std::chrono::milliseconds timespan(111605); // or whatever
std::this_thread::sleep_for(timespan);
获取当前时间
#include <sys/time.h>
struct timeval {
time_t tv_sec; /* seconds */
suseconds_t tv_usec; /* microseconds */
};
int gettimeofday (struct timeval * tv, struct timezone * tz);
#include <time.h>
#include <sys/time.h>
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec * 1000 + tv.tv_usec / 1000;
time_t time(time_t *t); // 获取从UNIX元年开始计数的秒数
struct tm *gmtime_r(const time_t *timep, struct tm *result); //不会考虑机器所在时区,GMT时间
struct tm *localtime_r(const time_t *timep, struct tm *result); // 会考虑机器所在时区/etc/timezone, 由于需要处理时区,速度会比gmtime_r慢, 可以在调用gmtime_r前手动加上时区偏移秒数(eg 北京时间: 8*60*60)
struct tm {
int tm_sec; /* Seconds (0-60) */
int tm_min; /* Minutes (0-59) */
int tm_hour; /* Hours (0-23) */
int tm_mday; /* Day of the month (1-31) */
int tm_mon; /* Month (0-11) */
int tm_year; /* Year - 1900 */
int tm_wday; /* Day of the week (0-6, Sunday = 0) */
int tm_yday; /* Day in the year (0-365, 1 Jan = 0) */
int tm_isdst; /* Daylight saving time */
};
time_t *timep 为日历时间(calendar time), 日历时间指距离1970-01-01 00:00:00 +0000 (UTC)的秒数
time_t local_time = time(NULL);
struct tm stime; //tm结构指针
localtime_r(&local_time, &stime); //获取当地日期和时间
// 线程不安全
#include <time.h>
time_t local_time = time(NULL);
struct tm* stime = localtime(&local_time);
std::localtime (非线程安全)
std::localtime is not thread-safe because it uses a static buffer (shared between threads)
localtime_r (线程安全)
时间格式化
size_t strftime(char *s, size_t max, const char *format, const struct tm *tm);
char *strptime(const char *s, const char *format, struct tm *tm);