如何使用 CTIME/Chrono Libarey 将开始时间与系统时钟进行比较

how can i compare a start time with the system clock using ctime/chrono libaray

本文关键字:系统 时间 时钟 比较 开始时 开始 CTIME 何使用 Chrono Libarey      更新时间:2023-10-16

我在尝试编译程序时遇到错误,并将从 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();
}