Skip to content

Commit

Permalink
opt(log): 优化log::AsyncSink,使用Buffer替代vector,使之更高效好用
Browse files Browse the repository at this point in the history
  • Loading branch information
hevake committed Jun 23, 2024
1 parent 793334e commit 466b007
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 17 deletions.
22 changes: 7 additions & 15 deletions modules/log/async_sink.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -59,30 +59,22 @@ void AsyncSink::onLogFrontEnd(const LogContent *content)

void AsyncSink::onLogBackEndReadPipe(const void *data_ptr, size_t data_size)
{
constexpr auto LogContentSize = sizeof(LogContent);
const char *p = reinterpret_cast<const char*>(data_ptr);

buffer_.reserve(buffer_.size() + data_size);
std::back_insert_iterator<std::vector<char>> back_insert_iter(buffer_);
std::copy(p, p + data_size, back_insert_iter);
buffer_.append(data_ptr, data_size);

bool is_need_flush = false;
while (buffer_.size() >= LogContentSize) {
auto content = reinterpret_cast<LogContent*>(buffer_.data());
auto frame_size = LogContentSize + content->text_len;
if (frame_size > buffer_.size()) //! 总结长度不够
while (buffer_.readableSize() >= sizeof(LogContent)) {
auto content = reinterpret_cast<LogContent*>(buffer_.readableBegin());
auto frame_size = sizeof(LogContent) + content->text_len;
if (frame_size > buffer_.readableSize()) //! 总结长度不够
break;
content->text_ptr = reinterpret_cast<const char *>(content + 1);
onLogBackEnd(content);
is_need_flush = true;
buffer_.erase(buffer_.begin(), (buffer_.begin() + frame_size));
buffer_.hasRead(frame_size);
}

if (is_need_flush) {
if (is_need_flush)
flushLog();
if (buffer_.capacity() > 1024)
buffer_.shrink_to_fit();
}
}

void AsyncSink::onLogBackEnd(const LogContent *content)
Expand Down
4 changes: 2 additions & 2 deletions modules/log/async_sink.h
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@

#include "sink.h"

#include <vector>
#include <tbox/util/async_pipe.h>
#include <tbox/util/buffer.h>

namespace tbox {
namespace log {
Expand All @@ -50,7 +50,7 @@ class AsyncSink : public Sink {
util::AsyncPipe async_pipe_;
bool is_pipe_inited_ = false;

std::vector<char> buffer_;
util::Buffer buffer_;
};

}
Expand Down

0 comments on commit 466b007

Please sign in to comment.