全然早くないが使い方間違ってる?
use std::env;
use std::fs;
use std::path::Path;
use std::fs::File;
use std::io::{self, BufRead, BufReader};
use std::time::Instant;
use threadpool::ThreadPool;
fn search_file(filename: String, search_string: String) -> Result<bool, Box<dyn std::error::Error>> {
for line in BufReader::new(File::open(filename.clone())?).lines() {
if line.unwrap().contains(&search_string) {
return Ok(true)
}
}
Ok(false)
}
fn get_files(dirname: &str) -> io::Result<Vec<String>> {
let mut entries: Vec<String> = Vec::new();
let dir = Path::new(dirname);
if dir.is_dir(){
for entry in fs::read_dir(dirname)? {
let e = entry?;
let p = e.path().file_name().unwrap().to_string_lossy().into_owned();
entries.push(p);
}
}
Ok(entries)
}
fn search_files_sequentially(file_locations: String, search_string: String) {
let entries: Vec<String> = get_files(&file_locations).unwrap();
for entry in entries {
let pass = format!("{}{}", file_locations, entry);
if search_file(pass, search_string.clone()).unwrap() {
println!("Found word in file: {}", entry);
}
}
}
fn search_files_concurrent(file_locations: String, search_string: String) {
let entries: Vec<String> = get_files(&file_locations).unwrap();
let pool = rayon::ThreadPoolBuilder::new().num_threads(4).build().unwrap();
for entry in entries {
let pass = format!("{}{}", file_locations, entry);
let mut value = search_string.clone();
pool.install(move || {
if search_file(pass, value).unwrap() {
println!("Found word in file: {}", entry);
}
});
}
}
fn main(){
let now = Instant::now();
search_files_sequentially("./src/".to_string(), "queue".to_string());
println!("{:?}", now.elapsed());
let now = Instant::now();
search_files_concurrent("./src/".to_string(), "queue".to_string());
println!("{:?}", now.elapsed());
}
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.02s
Running `target/debug/parallel queue`
Found word in file: pipeline.rs
Found word in file: main.rs
422.486µs
Found word in file: pipeline.rs
Found word in file: main.rs
701.462µs