A lightweight, header-only C++23 stopwatch utility for measuring code execution time with optional callbacks.
- RAII-based timing: Automatically measures elapsed time from construction to destruction
- Optional callbacks: Execute a function with the elapsed duration on scope exit
- std::format support: Format timing information using C++20
std::format - Source location tracking: Automatically captures where the timer was created
- Header-only: No compilation required, just include and use
- C++23 ready: Uses modern C++ features and best practices
- No copy/move semantics: Single ownership prevents accidental misuse
#include "siddiqsoft/timethis.hpp"
// Simple timing without callback
{
siddiqsoft::timethis timer;
// ... do work ...
auto elapsed = timer.elapsed();
}
// With callback
{
siddiqsoft::timethis timer([](const auto& duration) {
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(duration);
std::cout << "Operation took " << ms.count() << "ms\n";
});
// ... do work ...
} // Callback invoked here with elapsed time#include "siddiqsoft/timethis.hpp"
#include <format>
siddiqsoft::timethis timer;
std::this_thread::sleep_for(std::chrono::milliseconds(100));
std::cout << std::format("{}\n", timer);siddiqsoft::timethis timer;
std::this_thread::sleep_for(std::chrono::milliseconds(100));
std::cout << timer << std::endl; // Outputs: function_name took 100000000nsInstall-Package SiddiqSoft.TimeThis
FetchContent_Declare(
timethis
GIT_REPOSITORY https://github.com/SiddiqSoft/TimeThis.git
GIT_TAG main
)
FetchContent_MakeAvailable(timethis)
target_link_libraries(${PROJECT_NAME} timethis::timethis)cmake --preset Apple-Debug
cmake --build build/Apple-Debug./build/Apple-Debug/tests/timethis_testsApple-Debug/Apple-Release- macOS with LLVM 22+Linux-Clang-Debug/Linux-Clang-Release- Linux with ClangLinux-GCC-Debug/Linux-GCC-Release- Linux with GCCWindows-Debug/Windows-Release- Windows with MSVC
- C++23 compiler (Clang 18+, GCC 13+, MSVC 2022+)
- CMake 3.29+
BSD 3-Clause License - See LICENSE file for details