Linux下的时间函数

0. 写在前面

最近在做一个项目,频繁的需要使用到获取时间,包括相对时间、绝对时间等,发现C/C++和linux本身都提供了很多的API接口,看的眼花缭乱的,下面针对这些情况,我统一的做一下分类讲述。

1. 基本概念

  • 时间精度:

所谓时间精度,也成为时间颗粒,是指系统/函数所能给出的时间的最小单位;通常内核和应用层给出的时间精度各不相同:

  • 内核:tick(节拍)即CPUP的时钟定时器的一次终端;Jiffies用来记录自系统启动以来产生的节拍的总数,因此最小的时间颗粒为 Jiffies/Hz

2. Linux API

2.1 获取相对时间 (即系统起到后到目前的时间段)

1). sysinfo()

函数原型

#include <sys/sysinfo.h>    //头文件
int sysinfo(struct sysinfo *info);  //函数原型

结构体类型

struct sysinfo {  //结构体数据类型
           long uptime;               /* Seconds since boot */
           unsigned long loads[3];     /* 1, 5, and 15 minute load averages */
           unsigned long totalram;    /* Total usable main memory size */
           unsigned long freeram;      /* Available memory size */
           unsigned long sharedram;   /* Amount of shared memory */
           unsigned long bufferram;   /* Memory used by buffers */
           unsigned long totalswap;   /* Total swap space size */
           unsigned long freeswap;    /* swap space still available */
           unsigned short procs;      /* Number of current processes */
           char _f[22];               /* Pads structure to 64 bytes */
};

实例演示

#include <stdio.h>
#include <sys/sysinfo.h>
#include <time.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
    struct sysinfo info;
    char run_time[128];
    if (sysinfo(&info)) {
        fprintf(stderr, "Failed to get sysinfo, errno:%u, reason:%s\n",errno, strerror(errno));
        return -1;
    }
    long timenum=info.uptime;
    printf("The timenum=%ld\n", timenum);
    int runday=timenum/86400;
    int runhour=(timenum%86400)/3600;
    int runmin=(timenum%3600)/60;
    int runsec=timenum%60;
    bzero(run_time, 128);
    sprintf(run_time,"系统已运行:%d天%d时%d分%d秒",runday,runhour,runmin,runsec);
    printf("--->%s\n",run_time);
    return 0; 
}

运行结果

The timenum=127432
--->系统已运行:1天11时23分52秒

3. C lib

4. C++ STL

#include<iostream>
#include <chrono>
#include <thread>
#include <cstdint>
#include <cmath>
#include <ctime>
using namespace std;

class SimpleTime
{
public:
    typedef std::chrono::duration<long long, std::ratio<1,1000000> > macrosec_type;    
    typedef std::chrono::duration<long long, std::milli> millisec_type;    
    typedef std::chrono::duration<long long> seconds_type;    
    typedef std::chrono::duration<int, std::ratio<60> > minute_type;    
    typedef std::chrono::duration<int, std::ratio<60*60> > hour_type;    
    typedef std::chrono::duration<int, std::ratio<60*60*24> > day_type;    

public:
    SimpleTime(){ start(); }

    //sleep milliseconds / seconds
    void sleep_msec(double num){
        long long _num = static_cast<long long>(round(num)); 
        std::this_thread::sleep_for(std::chrono::milliseconds(_num));
    }
    void sleep_sec(double num) { double _num=num*1e3*1.0; sleep_msec(_num); }

    //Get the point time
    std::string get_date_string(){
        std::chrono::system_clock::time_point today = std::chrono::system_clock::now();
        time_t tt = std::chrono::system_clock::to_time_t(today);
        return ctime(&tt);
    }
    int get_timezone(){
        int timezone = 0;
        time_t t1, t2;
        struct tm *tm_local, *tm_utc;
    
        time(&t1);//返回从公元1970年1月1日的UTC时间从0时0分0秒算起到现在所经过的秒数
        tm_utc = gmtime(&t1);//返回的时间日期未经时区转换,格林尼治时间
        t2 = mktime(tm_utc);//转换为秒
        timezone = (t1 - t2) / 3600;
    
        return timezone;
    }

    //Get the milliseconds/seconds from epoch
    uint64_t since_epoch_msec(){
        std::chrono::time_point<std::chrono::system_clock, std::chrono::milliseconds> tp = \
            std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now());
        return (tp.time_since_epoch().count());
    }
    uint64_t since_epoch_sec(){
        return (static_cast<uint64_t>(round(since_epoch_msec()/1000)));
    }
    
    //Get the duration sinch system startup
    uint64_t elapsed_usec(){
        return static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now() - m_start).count());
    }   
    uint64_t elapsed_msec(){
        return static_cast<uint64_t>(round(elapsed_usec()/1000));
    }   
    uint64_t elapsed_sec(){
        return static_cast<uint64_t>(round(elapsed_usec()/1000000));
    }

    //restart the startup time 
    void start(){ m_start = std::chrono::steady_clock::now(); }

private:
    std::chrono::steady_clock::time_point m_start;
};

void sp(int j)
{
    SimpleTime tm;
    for(int i=1; i<100; i++)
    {
        tm.sleep_msec(2.5e3);
        cout<<j<<"The time is: TZ:"<<tm.get_timezone()<<" : " <<tm.get_date_string()<<endl;
        /*
        cout<<j<<" : sleep "<<2.5*i<<"seconds"<<endl;
        cout<<"Now time is: "<<tm.get_date_string() << '\n'<<"since epoch is:"<<tm.since_epoch_msec()<<"ms" <<"\n"<< " since_epoch: "<<tm.since_epoch_sec()<<" seconds"<<endl;

        cout<<"seconds elapsed: "<<tm.elapsed_sec()<<"s"<<endl;
        cout<<"mseconds elapsed: "<<tm.elapsed_msec()<<"ms"<<endl;
        cout<<"useconds elapsed: "<<tm.elapsed_usec()<<"us"<<endl;
        */
    }
}

int main()
{
    thread t1(sp, 1);
    thread t2(sp, 2);
    thread t3(sp, 3);
    while(true);
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,271评论 5 466
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,725评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,252评论 0 328
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,634评论 1 270
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,549评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 47,985评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,471评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,128评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,257评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,233评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,235评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,940评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,528评论 3 302
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,623评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,858评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,245评论 2 344
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,790评论 2 339

推荐阅读更多精彩内容