英文:
Rust function returning std::time::Instant
问题
I have a function that returns time elapsed.
I had originally tried
fn insert_test(Table: &mut HashMap<String, String>, items: &Vec<String>) -> std::time::Instant {
But the compiler errored on
^^^^^^^^ expected struct `Instant`, found `u128`
But the compiler tells me to use u128 instead.
But how would I know u128 ahead of time? https://doc.rust-lang.org/std/time/struct.Instant.html itself does not explicitly state its of type u128.
// inserts items onto the referenced datastruct and returns time elapsed
fn insert_test(Table: &mut HashMap<String, String>, items: &Vec<String>) -> u128 {
let t0 = Instant::now();
for i in items {
Table.insert(i.to_string(), "blahblah".to_string());
}
let duration = t0.elapsed().as_millis();
duration
}
英文:
I have a function that returns time elapsed.
I had originally tried
fn insert_test(Table: &mut HashMap<String,String>, items: &Vec<String>) -> std::time::Instant {
But the compiler errored on
^^^^^^^^ expected struct `Instant`, found `u128`
But the compiler tells me to use u128 instead
But how would I know u128 ahead of time? https://doc.rust-lang.org/std/time/struct.Instant.html itself does not explicitly state its of type u128
// inserts items onto the referenced datastruct and returns time elapsed
fn insert_test(Table: &mut HashMap<String,String>, items: &Vec<String>) -> u128 {
let t0 = Instant::now();
for i in items {
Table.insert(i.to_string(), "blahblah".to_string());
}
let duration = t0.elapsed().as_millis();
duration
}
答案1
得分: 4
你返回时间对象而不是原始数字的直觉是正确的。然而,时间经过更好地表示为Duration(时间差)而不是Instant(时间点)。
我建议将返回类型更改为 Duration 并移除 as_millis 调用。这是因为elapsed 返回的就是我们想要的Duration。
fn insert_test(Table: &mut HashMap<String, String>, items: &Vec<String>) -> std::time::Duration {
let t0 = Instant::now();
for i in items {
Table.insert(i.to_string(), "blahblah".to_string());
}
t0.elapsed()
}
英文:
Your instinct to return a time object rather than a raw number was a good one. However, time elapsed is better represented as a Duration (time delta) rather than an Instant (moment in time).
Instead of changing the return type I would remove the as_millis call. It works out nicely because elapsed returns a Duration, which is just what we want.
fn insert_test(Table: &mut HashMap<String, String>, items: &Vec<String>) -> std::time::Duration {
let t0 = Instant::now();
for i in items {
Table.insert(i.to_string(), "blahblah".to_string());
}
t0.elapsed()
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论