Skip to content

Instantly share code, notes, and snippets.

@TheCherno
Created October 21, 2024 03:45
Show Gist options
  • Save TheCherno/b2c71c9291a4a1a29c889e76173c8d14 to your computer and use it in GitHub Desktop.
Save TheCherno/b2c71c9291a4a1a29c889e76173c8d14 to your computer and use it in GitHub Desktop.
Timer
#include <chrono>
class Timer
{
public:
Timer() { Reset(); }
void Reset() { m_Start = std::chrono::high_resolution_clock::now(); }
float Elapsed() const { return std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - m_Start).count() * 0.001f * 0.001f; }
float ElapsedMillis() const { return std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - m_Start).count() * 0.001f; }
private:
std::chrono::time_point<std::chrono::high_resolution_clock> m_Start;
};
class ScopedTimer
{
public:
ScopedTimer(std::string_view name) : m_Name(name) {}
~ScopedTimer()
{
float time = m_Timer.ElapsedMillis();
std::cout << m_Name << " - " << time << "ms\n";
}
private:
Timer m_Timer;
std::string m_Name;
};
@matthewhelyar
Copy link

matthewhelyar commented Oct 30, 2024

#include <chrono>
#include <iostream>
#include <string>
#include <string_view>

@danikdanik
Copy link

danikdanik commented Nov 2, 2024

this allows you to specify the chrono units:

template<typename T>
T Elapsed() const
{
    return std::chrono::duration_cast<T>(std::chrono::high_resolution_clock::now() - start);
}

@Bricktech2000
Copy link

Recently made a similar thing in C using macro magic https://github.com/Bricktech2000/tictac.h :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment