Skip to content

Commit e7b0257

Browse files
authored
Lock-free updates for Histogram (#2951)
1 parent b6dcfe8 commit e7b0257

File tree

3 files changed

+23
-5
lines changed

3 files changed

+23
-5
lines changed

src/OpenTelemetry/CHANGELOG.md

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,13 @@
22

33
## Unreleased
44

5-
* Make `IResourceDetector` public to allow custom implementations of resource detectors.
5+
* Make `IResourceDetector` public to allow custom implementations of resource
6+
detectors.
67
([2897](https://github.com/open-telemetry/opentelemetry-dotnet/pull/2897))
78

9+
* Perf improvement for Histogram, by implementing lock-free updates.
10+
([2951](https://github.com/open-telemetry/opentelemetry-dotnet/pull/2951))
11+
812
## 1.2.0-rc2
913

1014
Released 2022-Feb-02

src/OpenTelemetry/Metrics/HistogramBuckets.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@ public class HistogramBuckets
3232

3333
internal double SnapshotSum;
3434

35+
internal int IsCriticalSectionOccupied = 0;
36+
3537
internal HistogramBuckets(double[] explicitBounds)
3638
{
3739
this.ExplicitBounds = explicitBounds;

src/OpenTelemetry/Metrics/MetricPoint.cs

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -323,11 +323,23 @@ internal void Update(double number)
323323
}
324324
}
325325

326-
lock (this.histogramBuckets.LockObject)
326+
var sw = default(SpinWait);
327+
while (true)
327328
{
328-
this.runningValue.AsLong++;
329-
this.histogramBuckets.RunningSum += number;
330-
this.histogramBuckets.RunningBucketCounts[i]++;
329+
if (Interlocked.Exchange(ref this.histogramBuckets.IsCriticalSectionOccupied, 1) == 0)
330+
{
331+
unchecked
332+
{
333+
this.runningValue.AsLong++;
334+
this.histogramBuckets.RunningSum += number;
335+
this.histogramBuckets.RunningBucketCounts[i]++;
336+
}
337+
338+
this.histogramBuckets.IsCriticalSectionOccupied = 0;
339+
break;
340+
}
341+
342+
sw.SpinOnce();
331343
}
332344

333345
break;

0 commit comments

Comments
 (0)