1 use std::{str::FromStr, time::Instant}; 2 3 use regex::Regex; 4 5 macro_rules! regex { 6 ($re:literal $(,)?) => {{ 7 static RE: once_cell::sync::OnceCell<regex::Regex> = once_cell::sync::OnceCell::new(); 8 RE.get_or_init(|| regex::Regex::new($re).unwrap()) 9 }}; 10 } 11 slow()12fn slow() { 13 let s = r##"13.28.24.13 - - [10/Mar/2016:19:29:25 +0100] "GET /etc/lib/pChart2/examples/index.php?Action=View&Script=../../../../cnf/db.php HTTP/1.1" 404 151 "-" "HTTP_Request2/2.2.1 (http://pear.php.net/package/http_request2) PHP/5.3.16""##; 14 15 let mut total = 0; 16 for _ in 0..1000 { 17 let re = Regex::new( 18 r##"^(\S+) (\S+) (\S+) \[([^]]+)\] "([^"]*)" (\d+) (\d+) "([^"]*)" "([^"]*)"$"##, 19 ) 20 .unwrap(); 21 let size = usize::from_str(re.captures(s).unwrap().get(7).unwrap().as_str()).unwrap(); 22 total += size; 23 } 24 println!("{}", total); 25 } 26 fast()27fn fast() { 28 let s = r##"13.28.24.13 - - [10/Mar/2016:19:29:25 +0100] "GET /etc/lib/pChart2/examples/index.php?Action=View&Script=../../../../cnf/db.php HTTP/1.1" 404 151 "-" "HTTP_Request2/2.2.1 (http://pear.php.net/package/http_request2) PHP/5.3.16""##; 29 30 let mut total = 0; 31 for _ in 0..1000 { 32 let re: &Regex = regex!( 33 r##"^(\S+) (\S+) (\S+) \[([^]]+)\] "([^"]*)" (\d+) (\d+) "([^"]*)" "([^"]*)"$"##, 34 ); 35 let size = usize::from_str(re.captures(s).unwrap().get(7).unwrap().as_str()).unwrap(); 36 total += size; 37 } 38 println!("{}", total); 39 } 40 main()41fn main() { 42 let t = Instant::now(); 43 slow(); 44 println!("slow: {:?}", t.elapsed()); 45 46 let t = Instant::now(); 47 fast(); 48 println!("fast: {:?}", t.elapsed()); 49 } 50