如何使用 CTIME/Chrono Libarey 将开始时间与系统时钟进行比较
how can i compare a start time with the system clock using ctime/chrono libaray
我在尝试编译程序时遇到错误,并将从 double 转换为 int。我想要的是能够不仅以秒为单位,而且以小时/分钟/秒为单位显示差异,但我想不出如何使 difftime 工作。如果有更好的选择,比如使用时间,我将不胜感激。
#include <chrono>
#include <ctime>
#include <iomanip>
#include <iostream>
int main() {
std::tm now{},;
std::chrono::system_clock::time_point cc;
std::cout << "enternyear month dayn";
std::cin >> now.tm_year >> now.tm_mon >> now.tm_mday;
now.tm_year -= 1900;
now.tm_mon -= 1;
std::time_t n = std::mktime(&now);
cc = std::chrono::system_clock::from_time_t(n);
n = std::chrono::system_clock::to_time_t(cc);
std::cout << std::put_time(std::localtime(&n), "%FT%T") << "n";
std::time_t system_time = time(nullptr);
std::cout << asctime(localtime(&system_time));
double fc = difftime(system_time, mktime(&now));
std::cout << "time diff "<< fc << endl;
}
你应该从霍华德·欣南特那里签出日期库。 https://github.com/HowardHinnant/date 其中的 tz lib 可以在不将其转换为 UTC 的情况下进行本地时间差异计算。(通常您应该在计算之前始终转换为 UTC,因为夏令时(它还包含格式函数,以小时分钟秒格式流式传输它。
更好的方法是使用steady_clock而不是system_clock。 我不知道你的任务是什么,但你可以使用另一个类,如秒表来生成经过的时间。
#include <chrono>
#include <ctime>
class StopWatch {
private:
chrono::time_point<chrono::steady_clock> start;
public:
void reset() { start = chrono::steady_clock::now(); }
StopWatch() { reset(); }
double elapsedSeconds() {
chrono::duration<double> d = chrono::steady_clock::now() - start;
return chrono::duration_cast<chrono::microseconds>(d).count() / 1000000.;
}};
之后,您可以简单地使用秒表:
int main(void){
Stopwatch s;
cout<<s.elapsedSeconds();
}
相关文章:
- c++ 11 如何获取系统时间?
- 如何使用跨平台代码在C++中设置系统时间?
- 将系统时间与变量进行比较 - C++
- 即使在多任务处理时,添加用户时间 + 系统时间(来自 shell 的时间命令)是否是一种可靠的措施?
- 系统时间从何而来?
- Qthread ::更改系统时间时睡眠不正常
- 在C++的主逻辑中接收真实/用户/系统时间
- 为什么在获取系统时间时在此处使用“atomic_signal_fence”
- 使用rdtsc计算系统时间
- 用C++设置windows系统时间
- 具有较低系统时间的C++时序方法
- 不取决于系统时间的时间
- 将系统时间 int 转换为格式化的时间字符串
- 在MFC对话框应用程序中全天候检查系统时间
- 执行循环,直到系统时间到达特定日期/时间
- 使用系统时间的随机数都是一样的
- C++ 在窗口中提升::时间与标准:自纪元(获取当前系统时间)以来的时间
- 获取系统时间(以毫秒为单位)作为int/double
- C++11打印当前系统时间(包括毫秒)
- 检查文件的上次写入时间是昨天由系统时间