Skip to content

Instantly share code, notes, and snippets.

@matovitch
Last active February 18, 2024 17:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matovitch/77125f1d42b75aa8b451c2e00b49ceea to your computer and use it in GitHub Desktop.
Save matovitch/77125f1d42b75aa8b451c2e00b49ceea to your computer and use it in GitHub Desktop.
#include <iostream>
#include <iomanip>
#include <chrono>
// Use it with | sort -n | grep -P 'CLK[01]'
namespace
{
void displayDuration(const std::chrono::nanoseconds duration)
{
std::cout << std::setw(3) << std::chrono::duration_cast<std::chrono::seconds >(duration).count() << "s "
<< std::setw(3) << std::chrono::duration_cast<std::chrono::milliseconds>(duration).count() % 1000 << "m "
<< std::setw(3) << std::chrono::duration_cast<std::chrono::microseconds>(duration).count() % 1000 << "u ";
}
}
struct Clock
{
Clock(const std::string_view name, bool isFull = false) :
_reference{std::chrono::steady_clock::now()},
_name{name},
_order{_ORDER++},
_total{0},
_isFull{isFull}
{
_LEVEL++;
}
void displayHeader()
{
std::cout << std::setfill('0') << std::setw(4) << _order << std::setfill(' ') << "CLK" << _LEVEL << ' ';
for (int i = 0; i < _LEVEL; i++)
{
std::cout << " ";
}
_order = _ORDER++;
}
void display()
{
auto diff = std::chrono::steady_clock::now() - _reference;
_total += diff;
if (_order > 9999)
{
std::cout << "0000CLK0 Too many events!\n";
std::cout << "9999CLK9 Too many events!\n";
}
displayHeader();
displayDuration(diff);
std::cout << std::right << std::setw(55 - 5 * _LEVEL) << _name << '\n';
}
void operator()(const std::string_view name)
{
display();
_name = name;
_reference = std::chrono::steady_clock::now();
}
~Clock()
{
display();
if (_isFull)
{
displayHeader();
for (int i = 0; i < 14; i++)
{
std::cout << '-';
}
std::cout << '\n';
displayHeader();
displayDuration(_total);
std::cout << '\n';
if (!_LEVEL)
{
displayHeader();
std::cout << "======================================================================\n";
}
}
_ORDER--;
_LEVEL--;
}
std::chrono::time_point<std::chrono::steady_clock> _reference;
std::string_view _name;
int _order;
std::chrono::nanoseconds _total;
bool _isFull;
static int _LEVEL;
static int _ORDER;
};
int Clock::_LEVEL = -1;
int Clock::_ORDER = 1;
#define CLK_MAKE_FULL(name) Clock clockWithSpecificName{#name, true /*print total*/}
#define CLK_MAKE(name) Clock clockWithSpecificName{#name}
#define CLK(name) clockWithSpecificName(#name)
#include <thread>
void toto()
{
using namespace std::chrono_literals;
CLK_MAKE(sleep #1);
std::this_thread::sleep_for(20ms);
CLK(sleep #2);
std::this_thread::sleep_for(10ms);
}
int main()
{
using namespace std::chrono_literals;
CLK_MAKE_FULL(sleep toto);
toto();
CLK(sleep #3);
std::this_thread::sleep_for(50ms);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment