Skip to content

Stopwatch is inconsistent when guarding against negative Elapsed durations #66734

@MihaZupan

Description

@MihaZupan

Stopwatch has the following code to detect negative elapsed durations, but this logic only runs during the Stopwatch.Stop call.

if (_elapsed < 0)
{
// When measuring small time periods the Stopwatch.Elapsed*
// properties can return negative values. This is due to
// bugs in the basic input/output system (BIOS) or the hardware
// abstraction layer (HAL) on machines with variable-speed CPUs
// (e.g. Intel SpeedStep).
_elapsed = 0;
}

If this behavior is worth preserving for stopped Stopwatch instances, I don't see why the responsibility should be shifted to the caller for "active" ones.

I believe this logic should either be removed entirely, or apply to all overloads regardless of IsRunning, possibly including the new GetElapsedTime helpers.

I wouldn't be surprised if some of our own logic is not accounting for the possibility of negative durations.

Metadata

Metadata

Assignees

Labels

area-System.Runtimebugin-prThere is an active PR which will close this issue when it is merged

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions