用chrono库写个方便使用的计时器
chrono库功能挺强大的,但是太长了不方便记忆使用,写个简单的计时工具库。
libjc
#pragma once
#ifndef LIBJC_H
#define LIBJC_H
#include <chrono>
namespace libjc
{
class jctime_duration;
class jctime_high_resolution_clock
{
private:
std::chrono::high_resolution_clock::time_point start_t;
std::chrono::high_resolution_clock::time_point stop_t;
unsigned char state;
public:
int start();
int stop();
libjc::jctime_duration duration() const;
libjc::jctime_duration operator-(const libjc::jctime_high_resolution_clock &) const;
jctime_high_resolution_clock();
// ~jctime_high_resolution_clock();
};
class jctime_duration
{
friend libjc::jctime_duration libjc::jctime_high_resolution_clock::operator-(const libjc::jctime_high_resolution_clock &) const;
friend libjc::jctime_duration libjc::jctime_high_resolution_clock::duration() const;
private:
std::chrono::nanoseconds rt;
public:
double tohour() const;
double tominute() const;
double tosecond() const;
double toms() const;
double tous() const;
long long int tons() const;
};
} // namespace libjc
#endif
libjc.cpp
#include "libjc"
namespace libjc
{
libjc::jctime_high_resolution_clock::jctime_high_resolution_clock()
{
this->state = 0;
}
libjc::jctime_duration jctime_high_resolution_clock::operator-(const jctime_high_resolution_clock &t) const
{
jctime_duration a;
a.rt = this->start_t - t.start_t;
return a;
}
int libjc::jctime_high_resolution_clock::start()
{
if (state == 1)
return 1;
this->start_t = std::chrono::high_resolution_clock::now();
state = 1;
return 0;
}
int libjc::jctime_high_resolution_clock::stop()
{
this->stop_t = std::chrono::high_resolution_clock::now();
state = 2;
return 0;
}
libjc::jctime_duration libjc::jctime_high_resolution_clock::duration() const
{
libjc::jctime_duration a;
a.rt = this->stop_t - this->start_t;
return a;
}
double libjc::jctime_duration::tohour() const
{
return std::chrono::duration<double, std::ratio<3600LL>>(rt).count();
}
double libjc::jctime_duration::tominute() const
{
return std::chrono::duration<double, std::ratio<60LL>>(rt).count();
}
double libjc::jctime_duration::tosecond() const
{
return std::chrono::duration<double>(rt).count();
}
double libjc::jctime_duration::toms() const
{
return std::chrono::duration<double, std::ratio<1LL, 1000LL>>(rt).count();
}
double libjc::jctime_duration::tous() const
{
return std::chrono::duration<double, std::ratio<1LL, 1000000LL>>(rt).count();
}
long long int libjc::jctime_duration::tons() const
{
return rt.count();
}
} // namespace libjc
使用方法:
#include <stdio.h>
#include "libjc"
int main()
{
// start the timer
libjc::jctime_high_resolution_clock tm1;
tm1.start();
// do some your own work
unsigned int a = ~(0);
int b = 0;
for (unsigned int i = 0; i < a; i++)
{
b++;
}
// stop the timer
tm1.stop();
auto da = tm1.duration();
// print the duration in different units
printf("time is :\n %lf s\n %lf hour \n %lf minutes \n %lf ms \n %lf us \n %lld ns\n",
da.tosecond(),
da.tohour(),
da.tominute(),
da.toms(),
da.tous(),
da.tons());
return 0;
}