我正在尝试使用 Rust 来加速 Python 程序,而我对这门语言完全是初学者。n我编写了一个函数,用于计算较大字符串中每个可能的长度字符串的出现次数。例如,如果主字符串是"AAAAT"and n=3,则结果将是 hashmap {"AAA":2,"AAT":1}。我使用 pyo3 从 Python 调用 Rust 函数。Rust函数的代码是:
fn count_nmers(seq: &str, n: usize) -> PyResult<HashMap<&str,u64>> {
let mut current_pos: usize = 0;
let mut counts: HashMap<&str,u64> = HashMap::new();
while current_pos+n <= seq.len() {
//print!("{}\n", &seq[current_pos..current_pos+n]);
match counts.get(&seq[current_pos..current_pos+n]) {
Some(repeats) => counts.insert(&seq[current_pos..current_pos+n],repeats+1),
None => counts.insert(&seq[current_pos..current_pos+n],1)
};
current_pos +=1;
}
//print!("{:?}",counts)
Ok(counts)
}
Run Code Online (Sandbox Code Playgroud)
当我对n( n<10) 使用较小的值时,Rust 比 Python 快一个数量级,但随着 n 长度的增加,差距趋于零,两个函数的速度相同n=200。(见图)
不同 n 聚体长度的计数时间(Python 黑、铁锈红) …