---
# System prepended metadata

title: Logger library 效能測試報告
tags: [MOXA]

---

---
tags: MOXA
---

# Logger library 效能測試報告

## 測試方式

寫兩萬筆資料到 log.txt (cout沒有資料到 log.txt)

## 測試結果

|                     |   poco    | poco-no-flush | loguru  |  cout  |
|:-------------------:|:---------:|:-------------:|:-------:|:------:|
|         SSD         |  25.706s  |    9.380s     | 75.751s | 2.606s |
|         HDD         | 1104.037s |    10.156s    | 74.895s | 2.452s |
| SSD-disable console |  12.295s  |    0.274s     | 0.114s  |   N/A   |
| HDD-disable console | 1096.522s |    0.259s     | 0.104s  |   N/A   |

## 評論

HDD，預設參數下，poco 平均一次寫 log.txt 需要 50ms 左右，非常差。

SSD，預設參數下，poco 平均一次寫 log.txt 需要 0.6ms 左右，效能可接受。

*目前已知 poco 的 flush 參數會嚴重影響log寫入效能，但是關閉 flush 的話，可能會 lose log when system crash，所以建議 debug 及開發階段打開此參數，在確保系統已經非常穩定沒有任何 crash 發生時，可關閉此 flush 參數


出處: https://pocoproject.org/docs/Poco.FileChannel.html#14448

> The flush property specifies whether each log message is flushed immediately to the log file (which may hurt application performance, but ensures that everything is in the log in case of a system crash), Valid values are:
> 
> true: Every essages is immediately flushed to the log file (default).
> false: Messages are not immediately flushed to the log file.

其他參考資料： https://github.com/pocoproject/poco/issues/2443

-> flush參數對於 Linux 效能沒有影響，但是會讓 Linux log.txt 更新不及時

> Without flushing:
100 writes = around 3ms on Windows
100 writes = around 8ms on Linux (NO content until channel closed)
>
>With flushing:
100 writes = around 106ms on Windows
100 writes = around 9ms on Linux - Content OK

## 程式碼

```C++=
#include "cnc_logger.hpp"

int main(int argc, char** argv) {
  string mode    = "cout";
  uint64_t times = 10000;
  tsn_cnc_v1::Logger::NamedVerbosity lv =
      tsn_cnc_v1::Logger::NamedVerbosity::Verbosity_INFO;
  tsn_cnc_v1::Logger::LoggerConfig config = tsn_cnc_v1::Logger::LoggerConfig();

  if (argc > 1) mode = argv[1];
  if (argc > 2) times = std::stoi(argv[2]);
  if (argc > 3) lv = tsn_cnc_v1::Logger::kNamedVerbosityMap.at(argv[3]);

  config.console_level = lv;
  config.flush         = false;

  if (mode == "poco") tsn_cnc_v1::init_loggeuru("log.txt", argc, argv, config);

  if (mode == "loguru") {
    loguru::g_stderr_verbosity =
        tsn_cnc_v1::kLoggerToLoguruVerbosityMap.at(config.console_level);
    loguru::init(argc, argv);
    loguru::add_file("log.txt", loguru::FileMode::Truncate,
                     loguru::Verbosity_MAX);
    for (auto i = 0; i < times; i++) LOG_F(INFO, "%d", i);
  } else {
    for (auto i = 0; i < times; i++) LOG_S(INFO) << i;
  }
}

```