spdlog-async.cpp 2.01 KB
Newer Older
gabime's avatar
gabime committed
1 2 3 4 5 6 7
//
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
//

#include <atomic>
#include <chrono>
8
#include <cstdlib>
gabime's avatar
gabime committed
9
#include <iostream>
gabime's avatar
gabime committed
10 11
#include <thread>
#include <vector>
gabime's avatar
gabime committed
12

gabime's avatar
gabime committed
13
#include "spdlog/async.h"
14
#include "spdlog/sinks/basic_file_sink.h"
15

gabime's avatar
gabime committed
16 17
using namespace std;

gabime's avatar
gabime committed
18
int main(int argc, char *argv[])
gabime's avatar
gabime committed
19 20
{
    using namespace std::chrono;
gabime's avatar
gabime committed
21
    using clock = steady_clock;
gabime's avatar
gabime committed
22 23

    int thread_count = 10;
gabime's avatar
gabime committed
24
    if (argc > 1)
25
        thread_count = std::atoi(argv[1]);
26

gabime's avatar
gabime committed
27
    int howmany = 1000000;
gabime's avatar
gabime committed
28 29
    spdlog::init_thread_pool(howmany, 1);

30
    auto logger = spdlog::create_async_logger<spdlog::sinks::basic_file_sink_mt>("file_logger", "logs/spdlog-bench-async.log", false);
31
    logger->set_pattern("[%Y-%m-%d %T.%F]: %L %t %v");
gabime's avatar
gabime committed
32

33 34 35 36 37 38
    std::cout << "To stop, press <Enter>" << std::endl;
    std::atomic<bool> run{true};
    std::thread stoper(std::thread([&run]() {
        std::cin.get();
        run = false;
    }));
39

gabime's avatar
gabime committed
40
    while (run)
gabime's avatar
gabime committed
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
        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;
                    logger->info("spdlog message #{}: This is some text for your pleasure", counter);
                }
            }));
        }

        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 = " << std::fixed << deltaf << " seconds" << std::endl;
        std::cout << "Rate = " << std::fixed << rate << "/sec" << std::endl;
gabime's avatar
gabime committed
72
    } // while
gabime's avatar
gabime committed
73

74
    stoper.join();
gabime's avatar
gabime committed
75

76
    return 0;
gabime's avatar
gabime committed
77
}