string_bench/
string-bench.rs

1use std::hint::black_box;
2use std::time::{Duration, Instant};
3
4use ftlog::{FtLogFormat, Record};
5
6const MIN_BENCH_TIME: u64 = 2000;
7const MESSAGES: usize = 100_000;
8
9macro_rules! run {
10    ($name: expr, $code: expr) => {
11        let mut sum_elapsed = Duration::default();
12        let mut count = 0u32;
13        loop {
14            let now = Instant::now();
15            for _ in 1..=MESSAGES {
16                black_box($code)
17            }
18            let elapsed = now.elapsed();
19            ftlog::logger().flush();
20
21            sum_elapsed += elapsed;
22            count += 1;
23            if sum_elapsed >= Duration::from_millis(MIN_BENCH_TIME) && count > 10 {
24                break;
25            }
26        }
27        println!(
28            "{},{}ns,{}/s",
29            $name,
30            (sum_elapsed / count / MESSAGES as u32).as_nanos(),
31            ((count as f64 * MESSAGES as f64) / sum_elapsed.as_secs_f64()).round()
32        );
33    };
34}
35struct StringFormatter;
36impl FtLogFormat for StringFormatter {
37    fn msg(&self, record: &Record) -> Box<dyn Send + Sync + std::fmt::Display> {
38        Box::new(format!(
39            "{} {}/{}:{} {}",
40            record.level(),
41            std::thread::current().name().unwrap_or_default(),
42            record.file().unwrap_or(""),
43            record.line().unwrap_or(0),
44            record.args()
45        ))
46    }
47}
48fn main() {
49    let _guard = ftlog::Builder::new()
50        .root(std::io::sink())
51        .format(StringFormatter)
52        .bounded(100_000, false)
53        // .unbounded()
54        .build()
55        .unwrap()
56        .init()
57        .unwrap();
58    run!("static string", {
59        ftlog::info!("ftlog message");
60    });
61    run!("with i32", {
62        ftlog::info!("ftlog: {}", 0i32);
63    });
64    run!("limit with i32", {
65        ftlog::info!(limit=3i64; "ftlog: {}", 0i32);
66    });
67}