muduo Timestamp详解

1. 简介

Timestamp用于提供时间戳相关的工具函数。

2. 类与接口

① string toString() const
返回时间的字符串形式,例如1649224501.687051

② string toFormattedString(bool showMicroseconds = true) const
返回时间的字符串形式,showMicroseconds为true时,例如20220406 05:55:01.687051,为false时,例如20220406 05:55:01

③ time_t secondsSinceEpoch() const
返回距离1970-1-1 00:00:00的秒数

④ static Timestamp now()
获取当前时间

⑤ double timeDifference(Timestamp high, Timestamp low)
获取时间间隔单位为秒

⑥ Timestamp addTime(Timestamp timestamp, double seconds)
从当前时间加上对应秒数

3. PRID64

c++使用PRID64,需要两步:
1.包含头文件:<inttypes.h>
2.定义宏:__STDC_FORMAT_MACROS,可以通过编译时加-D__STDC_FORMAT_MACROS,或者在包含文件之前定义这个宏。
int64_t用来表示64位整数,在32位系统中是long long int,在64位系统中是long int,所以打印int64_t的格式化方法是:

printf("%ld", value); // 64bit OS  
printf("%lld", value); // 32bit OS  

可借助PRID64实现跨平台的方法:

#include <inttypes.h>  
printf("%" PRId64 "\n", value);  
// 相当于64位的:  
printf("%" "ld" "\n", value);  
// 或32位的:  
printf("%" "lld" "\n", value);  
4. test_timestamp.cc
//
//  test_timestamp.cc
//  test_timestamp
//
//  Created by blueBling on 22-3-31.
//  Copyright (c) 2022年blueBling. All rights reserved.
//


#include "Timestamp.h"

#include <iostream>
#include <vector>

using std::cout;
using std::endl;
using std::vector;

int test_timestamp() {

	Timestamp time1(Timestamp::now());
	cout << time1.toString() << endl;
	cout << time1.toFormattedString(true) << endl;
	cout << time1.toFormattedString(false) << endl;

	// 创建1000000个Timestamp个对象所需要的时间
	const int kNumber = 1000*1000;
	std::vector<Timestamp> stamps;
	stamps.reserve(kNumber);

	for (int i = 0; i < kNumber; i++) {
		stamps.push_back(Timestamp::now());
	}

	cout << stamps.front().toFormattedString(false) << endl;
	cout << stamps.back().toFormattedString(false) << endl;
	cout << timeDifference(stamps.back(), stamps.front()) << endl;


	return 0;
}

int main() {

	test_timestamp();

	return 0;
}

测试结果

1649224501.687051
20220406 05:55:01.687051
20220406 05:55:01
20220406 05:55:01
20220406 05:55:01
0.064806
5. 源码

GitHub

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值