Skip to content

[API Proposal]: Stopwatch.GetElapsedTime #65858

@stephentoub

Description

@stephentoub

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

#48570

Risks

No response

Metadata

Metadata

Assignees

Labels

api-approvedAPI was approved in API review, it can be implementedarea-System.DiagnosticsenhancementProduct code improvement that does NOT require public API changes/additions

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions