// #pragma once
#include<chrono>
using namespace std::chrono;
namespace MyTimer
{
class Timer
{
public:
Timer() : m_begin(high_resolution_clock::now()) {}
void reset() {
m_begin = high_resolution_clock::now();
}
template<typename Duration = milliseconds>
int64_t elapsed() const
{
return duration_cast<Duration>(high_resolution_clock::now() - m_begin).count();
}
int64_t elapsed_nanos() const
{
return elapsed<nanoseconds>();
}
int64_t elapsed_micros() const
{
return elapsed<microseconds>();
}
int64_t elapsed_millis() const
{
return elapsed<milliseconds>();
}
int64_t elapsed_seconds() const
{
return elapsed<seconds>();
}
int64_t elapsed_minus() const
{
return elapsed<minutes>();
}
int64_t elapsed_hours() const
{
return elapsed<hours>();
}
private:
time_point<high_resolution_clock> m_begin;
};
}
#include<iostream>
#include<thread>
void test1()
{
::MyTimer::Timer t;
int num = 0;
for (int i = 0; i < 1000; ++i )
{
for(int j = 0; j < 100000; ++j) {
num += (i + j);
}
}
std::cout << t.elapsed() << std::endl;
std::cout << t.elapsed_nanos() << "ns" << std::endl;
}
int main()
{
::MyTimer::Timer t;
test1();
std::cout << t.elapsed_nanos() << "ns" << std::endl;
t.reset();
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << t.elapsed_nanos() << "nanos" << std::endl;
std::cout << t.elapsed_micros() << "micros" << std::endl;
std::cout << t.elapsed_millis() << "millis" << std::endl;
return 0;
}
C++实现的定时器
最新推荐文章于 2023-07-12 09:39:24 发布