Skip to content

Instantly share code, notes, and snippets.

@SmartArray
Last active November 27, 2019 12:09
Show Gist options
  • Save SmartArray/7014f8d2302b788e1a6ac8c1f04ec61f to your computer and use it in GitHub Desktop.
Save SmartArray/7014f8d2302b788e1a6ac8c1f04ec61f to your computer and use it in GitHub Desktop.
C++ TimingLogger (Java equivalent)

C++ equivalent for Androids Timing Logger

This snippet is a drop-in header

/**
 * Timing Logger, Author: Yoshi Jaeger
 * LICENSE: MIT
 */

#include <chrono>
#include <vector>
#include <iostream>
#include <sstream>

class TimingLogger {
public:
  TimingLogger(std::string name, bool accumulated = false) {
    this->name = name;
    this->start = std::chrono::high_resolution_clock::now();
    this->accumulated = accumulated;
  }

  void addSplit(std::string name) {
    struct pt meas;
    auto end = std::chrono::high_resolution_clock::now();
    meas.duration_ms = end - start;
    meas.name = name;

    measure_pts.push_back(meas);

    if (!accumulated) start = end;
  }

  void dumpToLog() {
    std::stringstream stream;
    dumpToStream(stream);

    std::cout << stream.str();
  }

  void dumpToStream(std::stringstream& stream) {
    stream << name << ": begin" << std::endl;

    for (auto i = 0; i < measure_pts.size(); ++i) {
      struct pt* meas = &measure_pts[i];
      stream << name << ":     ";
      stream << meas->duration_ms.count() * 1000 << " ms, " << meas->name << " " << std::endl;
    }

    auto end = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> diff = end - start;
    stream << name << ": end, " << diff.count() * 1000 << " ms" << std::endl;
  }
private:
  struct pt {
    std::string name;
    std::chrono::duration<double> duration_ms;
  };
  std::vector<struct pt> measure_pts;
  std::chrono::time_point<std::chrono::high_resolution_clock> start;
  std::string name;

  bool accumulated;
};

Usage example

int main() {
  TestTimingLogger logger("testTimingLogger");
  
  call1();
  logger.addSplit("call1");
   
  call2();
  logger.addSplit("call2");
  
  call3();
  logger.addSplit("call3");
    
  call4();
  logger.addSplit("call4");
  
  logger.dumpToLog();
}

Output sample

testTimingLogger: begin
testTimingLogger:     0.019 ms, call1 
testTimingLogger:     43.895 ms, call2 
testTimingLogger:     4023.11 ms, call3 
testTimingLogger:     1.388 ms, call4 
testTimingLogger: end, 0.776 ms

To receive the accumulated timing values, pass true as a second argument in the constructor.

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