Description
Proposal
Problem statement
We have a very common pattern in our code base when we're recording metrics that involve a span of time:
duration.as_millis() as f64 // CASE 1 - problematic because it loses the sub-milliseconds precision
duration.as_secs_f64() * 1000.0 // CASE 2 - preferred
Reminding people to use the second case so that preserve sub-millisecond precision is not very difficult, but I'd like to make it an even easier pattern for people to use and simply express that they want "the number of milliseconds as a floating point number, including the sub-millisecond values for precision".
Motivating examples or use cases
As far as I can tell, the .as_secs_f64() * 1000.0
is a very common pattern and it searching for it on Github returns hundreds of results (alt search for `*f32).
Doing a little research for this I realized people also write this as .as_nanos() as f64 / 1_000_000.0
, Github search yield some additional results.
Solution sketch
Ideally the new methods would include:
impl Duration {
pub fn as_millis_f64() -> f64;
pub fn as_millis_f32() -> f64;
}
I would also be interested in as_{micros,nanos}_{f64,f32}
from a completeness perspective, but I haven't seen this pattern as commonly for conversion to those units.
Alternatives
The main alternative I see is to continue using the duration.as_secs_f64() * 1000.0
. This alternative is quick to type and easy to understand.
Links and related work
A Github search provides some existing examples of Duration extension traits or other implementations, here are a couple:
What happens now?
This issue contains an API change proposal (or ACP) and is part of the libs-api team feature lifecycle. Once this issue is filed, the libs-api team will review open proposals as capability becomes available. Current response times do not have a clear estimate, but may be up to several months.
Possible responses
The libs team may respond in various different ways. First, the team will consider the problem (this doesn't require any concrete solution or alternatives to have been proposed):
- We think this problem seems worth solving, and the standard library might be the right place to solve it.
- We think that this probably doesn't belong in the standard library.
Second, if there's a concrete solution:
- We think this specific solution looks roughly right, approved, you or someone else should implement this. (Further review will still happen on the subsequent implementation PR.)
- We're not sure this is the right solution, and the alternatives or other materials don't give us enough information to be sure about that. Here are some questions we have that aren't answered, or rough ideas about alternatives we'd want to see discussed.