Linux C时间、日期函数总结框架

Linux 系统时间和日期函数

总览

Linux C时间、日期函数总结框架

各函数之间关系

Linux C时间、日期函数总结框架

其他相关时间函数:

ctime

将日期和时间转化成ASCII时间.

#include <time.h>

char *ctime(const time_t *timep);
char *ctime_r(const time_t *timep, char *buf);
  • 功能
    ctime(t) <=> asctime(localtime(t)), 转化calendar time t为一个null终结符, 其形式: "Wed Jun 9 15:03:10 2021n"
    ctime_r功能与ctime类似, 不过是将字符串存储到提供的缓存buf中, 要求其大小至少26byte

  • 参数
    ctime的参数是time_t类型的. time_t类型代表的是UTC时间, 即Epoch, 1970-01-01 00:00:00 +0000 (UTC) 到指定值的秒数.

  • 返回值
    ctime返回指定参数的UTC时间字符串
    ctime_r返回的UTC字符串内容同, 字符串地址就是buf地址

示例: 获取并打印当前时间UTC字符串

// 使用ctime
time_t stime;
time(&stime); // time()返回当前时间, time_t类型
char *s = ctime(&stime);
printf("%sn", s);

// 使用ctime_r
char buf[26] = {0};
char *s2 = ctime_r(&stime, buf);
printf("%sn", buf);
printf("%sn", s2);

printf("buf@%d return@%dn", buf, s2);

运行结果:

Wed Jun  9 15:23:51 2021

Wed Jun  9 15:23:51 2021

Wed Jun  9 15:23:51 2021

buf@1810803008 return@1810803008

asctime

将日期和时间, 转换成ASCII时间

#include <time.h>

char *asctime(const struct tm *tm);
char *asctime_r(const struct tm *tm, char *buf);
  • 功能
    asctime(tm)将细分时间tm转化成UTC时间字符串, 字符串形式同ctime;
    asctime_r(tm)功能同asctime, 不过会把字符串存入buf中;

  • 参数
    tm 包含了细分时间的各项值信息, 主要是年月日时分秒等, 其定义如下:

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 */
};
  • 返回值
    类同ctime.

clock

获取处理器时间, 常用于计算算法运行时间. 简单说, 就是处理器当前跑过的时钟数, 2个时间点对应时钟数相减, 就能得到这段时间所花费的时钟数, 如果能知道每个时钟所代表的时间含义, 就能求出具有实际物理意义的时间(秒/微妙等).
CLOCKS_PER_SEC 就是这样一个参数, 定义在<time.h>, 表示每秒钟的时钟数.

注意: sleep时, 进程会放弃CPU资源, 也就是说sleep所花费的时间, 不会计算在内.

#include <time.h>

clock_t clock(void);

示例: 计算算法所花费的时间

clock_t sclock;
clock_t eclock;
volatile int cnt = 0;

sclock = clock();

/* sleep 时间不会耗费clock */
sleep(2);

/* 1亿次 */
for (int i = 0; i < 1000000000; ++i) {
    cnt++;
}

eclock = clock();
printf("time = %lf secondsn", (eclock - sclock) / (double )CLOCKS_PER_SEC);

运行结果, 也表明, 利用sleep进程休眠了2s, 但最终运行时间计算结果 < 1s, 也就是说, sleep耗费时间不会计算在clock方式计算得到的时间.

time = 0.251695 seconds

原文链接: https://www.cnblogs.com/fortunely/p/14778950.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    Linux C时间、日期函数总结框架

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/403029

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年4月21日 上午11:20
下一篇 2023年4月21日 上午11:20

相关推荐