需要计算程序运行的时间,格式为 X天XX小时X分X秒,可以用这个类,在启动时初始化,需要时调用即可获得。
timeduration.h
//timeduration.h
#pragma once
#include <chrono>
#include <string>
using namespace std::chrono;
class Timeduration
{
public:
Timeduration() : m_begin(high_resolution_clock::now()){}
void reset() { m_begin = high_resolution_clock::now(); }
//默认输出秒
double elapsed() const
{
return duration_cast<duration<double>>(high_resolution_clock::now() - m_begin).count();
}
//默认输出毫秒
//int64_t elapsed() const
//{
//return duration_cast<chrono::milliseconds>(high_resolution_clock::now() - m_begin).count();
//}
//微秒
int64_t elapsed_micro() const
{
return duration_cast<microseconds>(high_resolution_clock::now() - m_begin).count();
}
//纳秒
int64_t elapsed_nano() const
{
return duration_cast<nanoseconds>(high_resolution_clock::now() - m_begin).count();
}
//秒
int64_t elapsed_seconds() const
{
return duration_cast<seconds>(high_resolution_clock::now() - m_begin).count();
}
//分
int64_t elapsed_minutes() const
{
return duration_cast<minutes>(high_resolution_clock::now() - m_begin).count();
}
//时
int64_t elapsed_hours() const
{
return duration_cast<hours>(high_resolution_clock::now() - m_begin).count();
}
//天
int64_t elapsed_days() const
{
typedef duration<int, std::ratio<86400,1> > days;
return duration_cast<days>(high_resolution_clock::now() - m_begin).count();
}
std::string elapsedString()
{
std::string retStr;
auto seconds = elapsed_seconds();
auto minutes = elapsed_minutes();
auto hours = elapsed_hours();
auto days = elapsed_days();
auto hour = hours - days * 24;
auto minute = minutes - hours * 60;
auto second = seconds - minutes * 60;
retStr = std::to_string(days) + "天"
+ std::to_string(hour) + "小时"
+ std::to_string(minute) + "分"
+ std::to_string(second) + "秒";
return std::move(retStr);
}
private:
time_point<high_resolution_clock> m_begin;
};
main.cpp
#include "timeduration.h"
#include <iostream>
#include <string>
#include <Windows.h>
Timeduration t_start;
using namespace std;
int main()
{
Sleep(2000);
std::cout<<t_start.elapsedString();
getchar();
return 0;
}
输出:
0天0小时0分2秒