log4cpp-bench-mt.cpp 2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
//
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
//

#include <atomic>
#include <chrono>
#include <iostream>
#include <memory>
#include <thread>
#include <vector>

#include "log4cpp/Appender.hh"
gabime's avatar
gabime committed
14 15
#include "log4cpp/BasicLayout.hh"
#include "log4cpp/Category.hh"
16 17 18
#include "log4cpp/FileAppender.hh"
#include "log4cpp/Layout.hh"
#include "log4cpp/PatternLayout.hh"
gabime's avatar
gabime committed
19
#include "log4cpp/Priority.hh"
20

gabime's avatar
gabime committed
21
int main(int argc, char *argv[])
22 23 24 25 26 27 28 29 30 31
{
    using namespace std::chrono;
    using clock = steady_clock;

    int thread_count = 10;
    if (argc > 1)
        thread_count = std::atoi(argv[1]);

    int howmany = 1000000;

gabime's avatar
gabime committed
32
    log4cpp::Appender *appender = new log4cpp::FileAppender("default", "logs/log4cpp-bench-mt.log");
33
    log4cpp::PatternLayout *layout = new log4cpp::PatternLayout();
34
    layout->setConversionPattern("%d{%Y-%m-%d %H:%M:%S.%l}: %p - %m %n");
35 36
    appender->setLayout(layout);

gabime's avatar
gabime committed
37
    log4cpp::Category &root = log4cpp::Category::getRoot();
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
    root.addAppender(appender);
    root.setPriority(log4cpp::Priority::INFO);

    std::atomic<int> msg_counter{0};
    std::vector<std::thread> threads;

    auto start = clock::now();
    for (int t = 0; t < thread_count; ++t)
    {
        threads.push_back(std::thread([&]() {
            while (true)
            {
                int counter = ++msg_counter;
                if (counter > howmany)
                    break;
                root << log4cpp::Priority::INFO << "log4cpp message #" << counter << ": This is some text for your pleasure";
            }
        }));
    }

    for (auto &t : threads)
    {
        t.join();
    }

    duration<float> delta = clock::now() - start;
    float deltaf = delta.count();
    auto rate = howmany / deltaf;

    std::cout << "Total: " << howmany << std::endl;
    std::cout << "Threads: " << thread_count << std::endl;
    std::cout << "Delta = " << deltaf << " seconds" << std::endl;
    std::cout << "Rate = " << rate << "/sec" << std::endl;

    root.shutdown();
    return 0;
}