我想要一个PrintDuration
函数来打印任务花费了多长时间,并允许用户指定打印的单位。示例用法:
auto start = std::chrono::system_clock::now();
std::this_thread::sleep_for(std::chrono::seconds(3));
PrintDuration<std::chrono::microseconds>(std::cout, start, "Waited for:");
它会打印出类似的东西:"Waited for: 3000000μs\n"
我的问题是:如何找到用户提供的单位?
目前,我正在使用以下内容:
template <class T>
std::intmax_t GetNum(const T& duration)
{
return T::period::num;
}
template <class T>
std::intmax_t GetDen(const T& duration)
{
return T::period::den;
}
typedef std::chrono::time_point<std::chrono::system_clock> TimePoint_t;
template <class Duration = std::chrono::seconds>
void PrintDuration(std::ostream& output,
const TimePoint_t& start,
std::string message)
{
auto duration = std::chrono::system_clock::now() - start;
auto convertedDuration = std::chrono::duration_cast<Duration>(duration);
auto count = convertedDuration.count();
std::string units("");
if (GetNum(convertedDuration) == 1)
{
if (GetDen(convertedDuration) == std::nano::den)
units = "ns";
else if (GetDen(convertedDuration) == std::micro::den)
units = "\u03BCs"; // us
else if (GetDen(convertedDuration) == std::milli::den)
units = "ms";
else if (GetDen(convertedDuration) == 1)
units = "s";
else
units = "";
}
else if(GetDen(convertedDuration) == 1)
{
if (GetNum(convertedDuration) == 60)
units = "m";
else if (GetNum(convertedDuration) == 3600)
units = "h";
else
units = "";
}
output << message << ' ' << count << units << '.' << std::endl;
}
虽然这很好用,但它似乎很冗长。我查看了 C++ 的文档,但找不到。任何帮助是极大的赞赏。