0

I coded a (recursive) function that took way too much time to execute. I was advised to use a "Profiler" so I created this Profiler class to check what operations take too much time.

#pragma once

#include "Timer.h"

#include <string>
#include <iostream>

class Profiler
{
public:
    static Profiler& instance() { //singleton.. sorry :P
        static Profiler prof;
        return prof;
    }

    void start(const std::string &operationName="") {
        _str = " ";
        _str += operationName;
        _timer.start();
    }

    void tell() {
        if(!_timer.running()) {
            std::cout << "Profiler::tell() called when timer wasn't running.\n";
            return;
        }

        std::cout << "It took" << _str << " " << _timer.elapsed() << " ms.\n";
        _timer.stop();
    }

private:
    Profiler() {}

    Timer _timer;
    std::string _str;
};

The issue is that although my recursive function still runs slow, all the output I get is 0 ms. Am I doing anything wrong? Should I use a more professional Profiler software?

McLovin
  • 3,295
  • 7
  • 32
  • 67
  • Showing us your `Timer` class is probably a good start. – Hatted Rooster Sep 19 '15 at 14:24
  • 2
    I wouldn't create a profiler; I'd buy one like dynaTrace or find an open source equivalent. – duffymo Sep 19 '15 at 14:26
  • You want to keep the timer running, and polling the current time, calculating the difference with the previous time. – Kenney Sep 19 '15 at 14:26
  • 1
    `GCC` has a built in [profiler](https://gcc.gnu.org/onlinedocs/libstdc++/manual/profile_mode.html) that can be analysed with [gprof](https://sourceware.org/binutils/docs/gprof/) – Galik Sep 19 '15 at 14:35
  • @JameyD It's nothing special. Just a std::clock() wrapper. – McLovin Sep 19 '15 at 14:36
  • @Kenney I don't get it. Can you show an example? – McLovin Sep 19 '15 at 14:36
  • Yes, but can you show us how you use your Profiler first? From your code, it would only work if you call `start("A"); slow_operation(); tell(); start("B"); ....` – Kenney Sep 19 '15 at 14:37
  • From the code you have shown use, either the `Timer` class doesn't time properly, or the run time **is** less than one tick of the clock. – Bo Persson Sep 19 '15 at 14:37
  • It is. That's the point. – McLovin Sep 19 '15 at 14:38
  • 1
    Yes you should use a proper profiler but in the meantime, try using `high_performance_clock` instead, although it's not guaranteed to be high enough resolution in practice. – mattnewport Sep 19 '15 at 15:32

0 Answers0