Skip to content

Very simple utility for recording the performance of blocks of code in C++

License

Notifications You must be signed in to change notification settings

nfergu/codetimer

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

10 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Introduction

CodeTimer is a very simple utility for recording the performance of blocks of code in C++. It lets us record timings against a specific key, and then aggregates all of the timings for a key.

CodeTimer is designed to perform well when called concurrently by multiple threads. Internally it uses a libcuckoo hash table.

CodeTimer meaures wall-clock time (as opposed to CPU time). It uses the <chrono> library's high_resolution_clock to measure timings with high precision.

Here is a simple usage example:

#include <chrono>
#include <iostream>
#include <thread>
#include "codetimer.h"
void sleepMillis(long milliseconds) {
    std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds));
}

int main () {

    auto start = std::chrono::high_resolution_clock::now();
    sleepMillis(100);
    CodeTimer::record("key1", start);

    start = std::chrono::high_resolution_clock::now();
    sleepMillis(200);
    CodeTimer::record("key2", start);

    start = std::chrono::high_resolution_clock::now();
    sleepMillis(300);
    CodeTimer::record("key1", start);

    CodeTimer::printStats();

    return 0;
}

When run this will produce something like the following:

key1: total=0.400211; occurrences=2
key2: total=0.200093; occurrences=1

For each key that we recorded a timing against, we can see the total time for that key, and the number of times we recorded a timing for the key.

In the above example we use CodeTimer::record to record a timing for a specific key, and CodeTimer::printStats() to print an aggregated view of the timings we have recorded. See the API docs in codetimer.h for more details.

Building and Running

To build the usage example, first build and install libcuckoo. Then, compile as follows:

g++ -o timerexample -std=c++11 timerexample.cc codetimer.cc codetimer.h

This assumes you have a version of GCC that supports C++ 11 installed.

You can then run the usage example as follows:

./timerexample

To use CodeTimer in your own projects, add #include "codetimer.h" to your source code, and add codetimer.h and codetimer.cc to your build.

License

CodeTimer is licensed under the Apache License, Version 2.0

About

Very simple utility for recording the performance of blocks of code in C++

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages