Nginx源码重作--时间 日期

1.源码

#ifndef _NGX_CLOCK_HPP
#define _NGX_CLOCK_HPP

//#include "Nginx.hpp"

class NgxClock final
{
public:
    NgxClock() = default;
    ~NgxClock() = default;
public:
    static const ngx_time_t& now()
    {
        ngx_time_update();

        return *ngx_timeofday();
    }

public:
    void reset()
    {
        m_time = now();
    }

    ngx_time_t delta() const
    {
        auto t = now();

        t.sec -= m_time.sec;
        t.msec -= m_time.msec;

        return t;
    }

    double elapsed() const
    {
        auto t = delta();

        return t.sec + t.msec * 1.0 / 1000;
    }
public:
    static decltype((ngx_current_msec)) msec()
    {
        return ngx_current_msec;
    }
public:
    static void sleep(ngx_uint_t sec)
    {
        ngx_msleep(sec * 1000);
    }

    static void msleep(ngx_uint_t msec)
    {
        ngx_msleep(msec);
    }
private:
    ngx_time_t m_time = now();
};

#endif  //_NGX_CLOCK_HPP

1.1类定义

class NgxClock final
{
public:
    NgxClock() = default;
    ~NgxClock() = default;
private:
    ngx_time_t m_time = now();
};

Ngxclock使用一个成员变量m_time来保存时间值,在构造时调用成员函数 now ()获取当前时间,表示计时的起点。

1.2操作函数

static const ngx_time_t& now ()
static const ngx_time_t& now()
    {
        ngx_time_update();

        return *ngx_timeofday();
    }
静态成员函数now ()首先调用ngx_time_update ( ),然后获取更新后的缓存时间:;
ngx_time_t delta () const
ngx_time_t delta() const
    {
        auto t = now();

        t.sec -= m_time.sec;
        t.msec -= m_time.msec;

        return t;
    }

     double elapsed() const

 {
        auto t = delta();

        return t.sec + t.msec * 1.0 / 1000;
    }

两个函数都是计算时间流逝

static decltype((ngx_current_msec)) msec()

声明类型:也是运行时间 封装ngx_current_msec

2.日期

class NgxDatetime final
{
public:
    NgxDatetime() = default;
    ~NgxDatetime() = default;
public:
    static std::time_t since()
    {
        return ngx_time();
    }

    static ngx_str_t today()
    {
        ngx_tm_t tm;

        //ngx_gmtime(since(), &tm);
        ngx_localtime(since(), &tm);

        static u_char buf[20] = {};

        auto p = ngx_snprintf(buf, 20,
                    "%d-%02d-%02d",
                    tm.ngx_tm_year, tm.ngx_tm_mon, tm.ngx_tm_mday);

        return ngx_str_t{static_cast<std::size_t>(p - buf), buf};
    }
public:
    static ngx_str_t http(std::time_t t = since())
    {
        static u_char buf[50] = {};

        auto p = ngx_http_time(buf, t);

        return ngx_str_t{static_cast<std::size_t>(p - buf), buf};
    }

    static std::time_t http(ngx_str_t& str)
    {
        return ngx_parse_http_time(str.data, str.len);
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值