nexes
nexes

Reputation: 23

c++ Log class inefficient?

I wrote a very simple Log class for a game im writing just to see some info in the terminal. But the way i did it bugs me because i feel its too inefficient. Every time i log something its constructor and destructor are called. So if i want to print the current frame rate (ex 60fps) the cont/desct are called 60 times a sec (creating and destroying 60 log objects a second). i dont want to keep passing a log object around the game every time i want to log something and i dont want to use signletons. is there a better solutions.

#include <iostream>
#include <sstream>


class Log
{
public:
    Log() : os()
    {

    }

    ~Log()
    {
        fprintf(stderr, "%s\n", os.str().c_str());
    }

    std::ostringstream &Write()
    {
        os << "from log class: " << 1337 << "\t";

        return os;
    }

private:
    std::ostringstream os;
};

int main(int argc, char *argv[])
{
    Log().Write() << "Hello world " << 45;

    return 0;
}

Upvotes: 0

Views: 208

Answers (2)

amdn
amdn

Reputation: 11582

You are making an assumption that the constructor and destructor are inefficient. In my experience if they are declared in a header file (as yours are) and if they are simple (as yours are) then you can trust the compiler to inline them and do a very good job. The call to printf is going to dominate the time.

Upvotes: 0

Victor Ronin
Victor Ronin

Reputation: 23268

I would recommend to go with some existing logging framework. People put a lot of efforts to make it as fast and as flexible as possible.

Here is good description of existing logging frameworks:

https://stackoverflow.com/questions/696321/best-logging-framework-for-native-c

Upvotes: 1

Related Questions