mirai/lib/cpp-utils/debug.h

66 lines
1.4 KiB
C
Raw Normal View History

2024-04-30 16:57:34 +02:00
/*
* Mirai. Copyright (C) 2024 Vyn
* This file is licensed under version 3 of the GNU General Public License (GPL-3.0-only)
* The license can be found in the LICENSE file or at https://www.gnu.org/licenses/gpl-3.0.txt
*/
#ifndef CPP_UTILS_DEBUG_H
#define CPP_UTILS_DEBUG_H
#include <algorithm>
#include <chrono>
#include <iostream>
#include <ostream>
#include <string>
namespace cpputils::debug
{
class Timer
{
public:
2024-05-04 17:38:23 +02:00
Timer() : startTime(std::chrono::steady_clock::now())
2024-04-30 16:57:34 +02:00
{
}
void start()
{
2024-05-04 17:38:23 +02:00
startTime = std::chrono::steady_clock::now();
2024-04-30 18:18:54 +02:00
isRunning = true;
2024-04-30 16:57:34 +02:00
}
2024-04-30 18:18:54 +02:00
void stop()
2024-04-30 16:57:34 +02:00
{
2024-05-04 17:38:23 +02:00
const auto now = std::chrono::steady_clock::now();
2024-08-16 21:35:12 +02:00
duration += std::chrono::duration_cast<std::chrono::milliseconds>(now - startTime).count();
2024-04-30 18:18:54 +02:00
isRunning = false;
}
void reset()
{
duration = 0;
isRunning = false;
}
void printTimeElapsed(const std::string &message) const
{
long durationToShow = duration;
if (isRunning) {
2024-05-04 17:38:23 +02:00
const auto now = std::chrono::steady_clock::now();
2024-04-30 18:18:54 +02:00
durationToShow +=
2024-08-16 21:35:12 +02:00
std::chrono::duration_cast<std::chrono::milliseconds>(now - startTime).count();
2024-04-30 18:18:54 +02:00
}
2024-08-16 21:35:12 +02:00
std::cout << "[Debug - Timer] " << message << ": " << durationToShow << " ms" << std::endl;
2024-04-30 16:57:34 +02:00
}
private:
2024-05-04 17:38:23 +02:00
std::chrono::time_point<std::chrono::steady_clock, std::chrono::nanoseconds> startTime;
2024-04-30 18:18:54 +02:00
// Timer are always running when created. You can use .reset() after creation.
bool isRunning = true;
2024-08-16 21:35:12 +02:00
long duration = 0;
2024-04-30 16:57:34 +02:00
};
} // namespace cpputils::debug
#endif