Skip to content

Commit

Permalink
add benches code
Browse files Browse the repository at this point in the history
  • Loading branch information
baoyachi committed Jun 5, 2024
1 parent 4a04ca3 commit 4a4d0d6
Show file tree
Hide file tree
Showing 4 changed files with 50 additions and 1 deletion.
5 changes: 5 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@ winnow = "0.6.8"

[dev-dependencies]
serde_json = { version = "1.0.87" }
criterion = "0.3"

[[bench]]
name = "parser_benchmark"
harness = false

# docs.rs-specific configuration
[package.metadata.docs.rs]
Expand Down
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,12 @@
# parse string to std::time::Duration
========================================
<p align="center">
<img
width="200"
src="https://raw.githubusercontent.com/baoyachi/duration-str/master/duration-str.png"
alt="duration-str parser"
/>
</p>

[![Chrono GitHub Actions](https://github.com/baoyachi/duration-str-rs/actions/workflows/check.yml/badge.svg)](https://github.com/baoyachi/duration-str-rs/actions?query=workflow%3Abuild)
[![Crates.io](https://img.shields.io/crates/v/duration-str.svg)](https://crates.io/crates/duration-str)
Expand Down
36 changes: 36 additions & 0 deletions benches/parser_benchmark.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
use criterion::{criterion_group, criterion_main, Criterion};
use std::time::Duration;
use winnow::ascii::{digit1, multispace0};
use winnow::error::ContextError;
use winnow::token::literal;
use winnow::Parser;

fn parse_duration() {
let duration = duration_str::parse("2h 37m").unwrap();
assert_eq!(duration, Duration::new(9420, 0))
}

fn impeccable_duration() {
let input = "2h 37m";
(
digit1::<_, ContextError>.try_map(str::parse::<usize>),
literal('h').value(3600),
multispace0,
digit1.try_map(str::parse::<usize>),
literal('m').value(60),
)
.map(|(hour, h_unit, _, min, min_unit)| hour * h_unit + min * min_unit)
.parse(input)
.unwrap();
}

pub fn duration_str_benchmark(c: &mut Criterion) {
c.bench_function("duration_str", |b| b.iter(|| parse_duration()));
}

pub fn impeccable_benchmark(c: &mut Criterion) {
c.bench_function("impeccable", |b| b.iter(|| impeccable_duration()));
}

criterion_group!(benches, duration_str_benchmark, impeccable_benchmark);
criterion_main!(benches);
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#![doc(
html_logo_url = "https://raw.githubusercontent.com/baoyachi/duration-rs/master/duration-str.png"
html_logo_url = "https://raw.githubusercontent.com/baoyachi/duration-str/master/duration-str.png"
)]
//! Parse string to `Duration` .
//!
Expand Down

0 comments on commit 4a4d0d6

Please sign in to comment.