我目前正在C ++中进行练习,我将创建一个名为TimerClass的结构,该结构的构造函数记录当前时间,并创建一个析构函数,该析构函数记录该当前时间并从构造时间中减去该时间(即,构造函数中的当前时间)并将其打印到控制台。这是我到目前为止的代码:
#include <cstdio>
#include <cstring>
#include <iostream>
#include <chrono>
#include <ctime>
struct TimerClass {
TimerClass(time_t* timestamp) : timestamp(timestamp) {
std::chrono::system_clock::now();
printf("The current time is: %s\n", timestamp);
}
~TimerClass() {
printf("Time since last construction: %s\n", timestamp);
}
private:
time_t* timestamp;
};
我尝试过在线寻找一些可能的解决方案,但运气不佳。我是C ++的新手,我正在学习的书没有说如何记录时间。
std :: chrono库对于您的方案是一个不错的选择。steady_clock
此类工作比较好,因为它不受系统时间的影响,因此在演示中使用了它。
另一个提示,除非没有其他选择,否则不要再使用指针。带有“ c”前缀的标头表示来自C语言的库,因此最好避免使用它们。
这是演示,也许是您了解chrono库的起点。
#include <iostream>
#include <chrono>
#include <thread>
struct TimerClass {
TimerClass()
: m_start { std::chrono::steady_clock::now() }
{}
~TimerClass() {
using namespace std::chrono;
auto life = steady_clock::now() - m_start;
std::cout << "Duration in ms " << duration_cast<milliseconds>( life ).count() << std::endl;
std::cout << "Duration in us " << duration_cast<microseconds>( life ).count() << std::endl;
}
private:
std::chrono::steady_clock::time_point m_start;
};
int main()
{
TimerClass t;
{
TimerClass t_2;
std::this_thread::sleep_for( std::chrono::seconds { 1 } );
}
std::this_thread::sleep_for( std::chrono::milliseconds { 300 } );
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句