Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

多线程logging性能的测试与优化 #32

Open
sunxfancy opened this issue Jul 4, 2024 · 2 comments
Open

多线程logging性能的测试与优化 #32

sunxfancy opened this issue Jul 4, 2024 · 2 comments

Comments

@sunxfancy
Copy link
Owner

sunxfancy commented Jul 4, 2024

@bfjm 之前你提到的关于log多线程写入的问题,现在代码中的实现还比较粗糙,只有一个简单的lock-free的队列。并且你说的没错,很多log系统在多线程处理时,都会使用额外的线程来异步写入来避免对原有工作的干扰,这点非常有必要。

也许你可以帮忙建立一个多线程的写入的benchmark,测试一下性能和可靠性,并研究一下怎么样优化log的写入。我们的Test Case是可以添加Benchmark的,在test/log_test.cpp下,有一个这样的一段代码就是用来测试性能的:

BENCHMARK("speedtest") {
#ifdef ZEROERR_OS_UNIX
    uint64_t* data      = new uint64_t[1000000];
    FILE*     file      = fmemopen(data, 1000000 * sizeof(uint64_t), "w");
    FILE*     oldstdout = stdout;
    FILE*     oldstderr = stderr;
    stdout = stderr = file;
#endif
    zeroerr::LogStream::getDefault().setFlushManually();
    std::stringstream ss;
    Benchmark         bench("log speed test");
    bench.run("spdlog", [] { spdlog::info("hello world {:03.2f}", 1.1); })
        .run("stringstream",
             [&] {
                 ss << "hello world " << 1.1;
                 doNotOptimizeAway(ss);
             })
        .run("log", [] { LOG("hello world {value}", 1.1); })
        .report();
    zeroerr::LogStream::getDefault().setFlushAtOnce();

#ifdef ZEROERR_OS_UNIX
    stdout = oldstdout;
    stderr = oldstderr;
    fclose(file);
    delete[] data;
#endif
}

不过对于像一些高级profiling的功能,只有linux下才能用perf库收集。我一直想让这个东西支持windows,但无奈windows硬件寄存器太难读取了,我写了一些单独的测试代码去收集硬件信息,但一直没能找到将其整合起来的方法。如果你有兴趣也可以看下 https://github.com/sunxfancy/Win32Perf ,不过这个功能优先级比较低,并不是那么紧要。

@bfjm
Copy link

bfjm commented Jul 8, 2024

@sunxfancy 我总结了一下 lock-free queue可以分类以下几类
SPSC : 单个生产者,单个消费者,不用加锁
MPSC : 多个生产者,多个消费者,这种情况可以拆解成多个SPSC的情况,也可以不用加锁
MPMC : 多个生产者,多个消费者,concurrentqueue ,的做法是每个p和c都有一个token,在自己的token上生产消费,可以不用加锁。
SPMC: 单个生产者,多个消费者,这种需要维护多个C的token,也可以不用加锁。

根据上面情况,我们是否可以对C的数量进行配置,一个C对应一个thread,可以参考disruptor, 另外MPMC的情况,比较复杂,考虑是否需要引入第三方库。

@sunxfancy
Copy link
Owner Author

对于日志的应用场景,我觉得一个线程用来向文件中写入应该已经足够了,我们可能不用考虑多个消费者的情况,而这样能简化一下设计。对于内存中日志的访问,我们最大的应用场景也是在日志收集后再访问,这样可以避免过多复杂情况的出现。我们这个库是一个比较精简的日志系统,我不太希望通过引入第三方库来解决问题,因为这会让我们更难做成header-only并且降低易用性。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants