Rust读取小文件性能不及C?求优化方案
Rust读取CSV文件的性能优化问题
我正在把一段C代码改写为Rust,遇到了小文件读取的性能瓶颈:目标是一个600万行、150MB的4列CSV文件,C语言读取耗时约0.35秒,但在同一台机器上,Rust用--release编译后耗时1.9秒。我最初用基础的BufReader遍历行实现,代码如下:
// 用Result包裹输出以处理错误,返回文件行的迭代器 fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>> where P: AsRef<Path>, { let file = File::open(filename)?; Ok(io::BufReader::new(file).lines()) } fn main() { // 当前路径下需存在data_summary_6m.csv文件 let start = Instant::now(); let started_assigning = start.elapsed(); let mut count = 0; if let Ok(lines) = read_lines("./data_summary_6m.csv") { // 消费迭代器,返回可选的String for line in lines.flatten() { count += 1; } } let finished_assigning = start.elapsed(); println!("{:?}, Run time\n", finished_assigning - started_assigning); println!("{:?}, Counted rows\n", count); }
程序输出:
1.898065676s, Run time 6000001, Counted rows
我已经查阅过相关StackOverflow线程,尝试了BufReader实现、参考示例教程以及serde方案。
更新1:改用read_line后的变化
按照建议改用read_line后,遍历耗时大幅降至500ms,但循环内用split和迭代器分割列的耗时显著增加,代码如下:
let file = File::open("./data_summary_60m.csv")?; let mut reader = BufReader::new(file); let mut string = String::new(); while reader.read_line(&mut string)? > 0 { let mut line = string.split(","); let col1 = line.next(); let col2 = line.next(); let col3 = line.next(); let col4 = line.next(); }
更新2:给Rust新手的提醒
必须使用--release模式编译运行代码,仅用-r flag编译无效,正确命令为:
cargo build -r
随后执行:
cargo run -r
请问我还遗漏了哪些优化点?
内容的提问来源于stack exchange,提问作者kkrapic
相关产品推荐
相关产品推荐

