c11时间库一个小例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#pragma once
#include <chrono>
#include <string>
#include <iostream>
#include <ctime>
#include <iomanip>
 
#define NAMESPACE(x) namespace x{
#define NAMESPACEEND(x) }
 
 
NAMESPACE(DEF)
 
const int kMicroSecondsPerSecond = 1000 * 1000;
 
class Timestamp
{
public:
    Timestamp() {};
    void TimestampSet(const Timestamp& t) {
        time_ = t.time_;
    };
 
    bool valid() const { return time_.time_since_epoch().count() > 0; }
    int64_t MicroSecondsSinceEpoch() const { return time_.time_since_epoch().count(); }
    void Now() { time_  = std::chrono::system_clock::now();};
    std::string Timestamp::ToFormattedString() const;
    std::string ToString() const {
        char buf[32] = { 0 };
        auto s1 = std::chrono::duration_cast<std::chrono::microseconds>
                 (time_.time_since_epoch()).count();   
        snprintf(buf, sizeof(buf) - 1, "%lld.%06lld", s1 / kMicroSecondsPerSecond, s1 % kMicroSecondsPerSecond);
        //printf("buf %s\n", buf);
        return buf;
    };
    const std::chrono::time_point<std::chrono::system_clock>&
        Time() { return time_; };
private:
    std::chrono::time_point<std::chrono::system_clock>  time_;
};
 
inline bool operator<(Timestamp lhs, Timestamp rhs)
{
    return lhs.Time() < rhs.Time();
}
 
inline bool operator==(Timestamp lhs, Timestamp rhs)
{
    return lhs.Time() == rhs.Time();
}
 
inline bool operator>(Timestamp lhs, Timestamp rhs)
{
    return lhs.Time() > rhs.Time();
}
 
inline bool operator>=(Timestamp lhs, Timestamp rhs)
{
    return lhs.Time() >= rhs.Time();
}
 
inline int64_t timeDifference(Timestamp high, Timestamp low)
{
    return  (high.Time() - low.Time()).count();
}
 
 
 
std::string Timestamp::ToFormattedString() const
{
    auto t = std::chrono::system_clock::to_time_t(time_);
 
    char mbstr[100] = {0};
    if (std::strftime(mbstr, sizeof(mbstr), "%Y_%m_%d_%H_%M_%S", std::localtime(&t)))
    {
        return mbstr;
    }
 
    return mbstr;
}
 
NAMESPACEEND(DEF)

 

/**************************************************************
技术博客
http://www.cnblogs.com/itdef/
 
技术交流群
群号码:324164944
 
欢迎c c++ windows驱动爱好者 服务器程序员沟通交流
**************************************************************/

posted on   itdef  阅读(375)  评论(0编辑  收藏  举报

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示