spdlog/example/utils.h

55 lines
1.3 KiB
C
Raw Normal View History

2014-01-25 21:52:10 +08:00
#pragma once
#include <functional>
#include <chrono>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <locale>
2014-02-22 04:51:54 +08:00
namespace utils {
2014-01-25 21:52:10 +08:00
template<typename T>
std::string format(const T& value)
{
static std::locale loc("");
std::stringstream ss;
ss.imbue(loc);
ss << value;
return ss.str();
}
2014-01-25 23:28:56 +08:00
inline void bench(const std::string& fn_name, const std::chrono::milliseconds &duration, const std::function<void() >& fn)
2014-01-25 21:52:10 +08:00
{
using namespace std::chrono;
typedef steady_clock the_clock;
size_t counter = 0;
seconds print_interval(1);
auto start_time = the_clock::now();
auto lastPrintTime = start_time;
2014-02-22 04:51:54 +08:00
while (true) {
2014-01-25 21:52:10 +08:00
fn();
++counter;
auto now = the_clock::now();
if (now - start_time >= duration)
break;
2014-02-22 04:51:54 +08:00
if (now - lastPrintTime >= print_interval) {
2014-01-25 23:28:56 +08:00
std::cout << fn_name << ": " << format(counter) << " per sec" << std::endl;
2014-01-25 21:52:10 +08:00
counter = 0;
lastPrintTime = the_clock::now();
}
}
}
2014-01-25 23:28:56 +08:00
inline void bench(const std::string& fn_name, const std::function<void() >& fn)
{
using namespace std::chrono;
auto start = steady_clock::now();
fn();
auto delta = steady_clock::now() - start;
std::cout << fn_name << ": " << duration_cast<milliseconds>(delta).count() << " ms" << std::endl;
}
2014-01-29 10:08:58 +08:00
}