-
Notifications
You must be signed in to change notification settings - Fork 5.3k
Closed
Labels
api-approvedAPI was approved in API review, it can be implementedAPI was approved in API review, it can be implementedarea-System.DiagnosticsenhancementProduct code improvement that does NOT require public API changes/additionsProduct code improvement that does NOT require public API changes/additions
Milestone
Description
Background and motivation
Stopwatch is a class and allocates, but when used for precision timing, you often don't want the overhead of that allocation, and it can be ergonomically inconvenient to try to cache an instance away somewhere. Developers that want to avoid that allocation end up using Stopwatch.GetTimestamp() directly, at which point they're having to remember what math to do and repeatedly do it for computing a TimeSpan from two timestamps. We can expose a helper to make that easier.
API Proposal
namespace System.Diagnostics
{
public class Stopwatch
{
+ public static TimeSpan GetElapsedTime(long startingTimestamp) => GetElapsedTime(startTimestamp, Stopwatch.GetTimestamp());
+ public static TimeSpan GetElapsedTime(long startingTimestamp, long endingTimestamp) => new TimeSpan((long) ((endTimestamp - startTimestamp) * s_tickFrequency) );
}
}(based on the discussion in #48570 (comment))
API Usage
long starting = Stopwatch.GetTimestamp();
...
long ending = Stopwatch.GetTimestamp();
...
TimeSpan time = Stopwatch.GetElapsedTime(starting, ending);or
long starting = Stopwatch.GetTimestamp();
...
TimeSpan time = Stopwatch.GetElapsedTime(starting);Alternative Designs
Risks
No response
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
api-approvedAPI was approved in API review, it can be implementedAPI was approved in API review, it can be implementedarea-System.DiagnosticsenhancementProduct code improvement that does NOT require public API changes/additionsProduct code improvement that does NOT require public API changes/additions