CPU profiling .NET 10 services: EventPipe stack sampling with dotnet-trace, flame graphs and call trees in PerfView, Speedscope and Visual Studio, inclusive vs exclusive time, wall-clock vs CPU time, and turning a hot path into a verified fix.
dotnet-trace with the default cpu-sampling profile uses EventPipe's sample profiler: roughly every millisecond it records each managed thread's call stack. Aggregated, those samples become a call tree or flame graph, where a frame's width is the share of samples it appears in.
I read it top-down from my entry point to find the wide paths, then bottom-up by exclusive (self) time to find the methods that actually burn CPU.
A wide frame is not always CPU work: EventPipe also samples threads that are waiting on a lock or I/O, and an awaiting async request holds no thread, so it doesn't appear at all. I cross-check with dotnet-counters and distributed traces. The trade-off: sampling is cheap enough for production but statistical, so short events can be missed; I capture under real load for 30–60 seconds and verify fixes with a second profile.
"CPU profiling in .NET is statistical sampling. When I run
dotnet-trace collect --profile cpu-sampling, the runtime's sample profiler suspends managed threads roughly every millisecond and records their stacks. Nothing is instrumented, so overhead is a few percent, and the result is a .nettrace file of thousands of stacks. A method that appears in 30% of samples was on the stack 30% of the time.I look at it two ways. Top-down, as a call tree or flame graph starting from the request entry point, I follow the widest tower: which controller, which service, which call inside it. Bottom-up, sorted by exclusive time, I see which methods have their own code on the CPU, which often points straight at something like
Regexconstruction, JSON serialisation or a LINQContainsover a list. For example, at [company] [a pricing endpoint spent 38% of its samples inRegex..ctorbecause a pattern was built per call]; making it a static, source-generated regex cut CPU by [a third].The mistake I see is reading every wide frame as CPU work. EventPipe samples blocked threads too, so
Monitor.EnterorWaitHandle.WaitOnecan look 'hot' when the thread is just waiting. I check that againstdotnet-counters: if CPU is low and the wide frames are waits, it's a contention or I/O problem, not a compute one. And I always re-profile after the fix: the frame should get narrower, and p95 or CPU per request should move."
| View | Shows | Use it to |
|---|---|---|
| Flame graph (Speedscope 'Left Heavy', VS) | Merged stacks; width = samples | Spot the widest paths fast |
| Call tree (PerfView CallTree, VS) | Inclusive % per node, expandable | Walk down from your entry point |
| By name / bottom-up (PerfView ByName, VS Functions) | Exclusive % per method | Find the code doing the work |
| Caller/callee | Who calls a hot method | Decide which caller to change |
| Time order (Speedscope 'Time Order') | Samples over time per thread | Find bursts, stalls and GC pauses |
| Inclusive | Exclusive | |
|---|---|---|
| Counts | Method + all callees | Method's own instructions |
| High value means | This path is expensive | This method itself is expensive |
| Typical example | OrderController.Get 80% |
Dictionary.FindValue 12% |
| Tool | Strength |
|---|---|
| PerfView | Deepest analysis, grouping and folding, diffing two traces; Windows |
Speedscope (--format speedscope) |
Browser-based flame graphs, any OS |
| Visual Studio Performance Profiler | Opens .nettrace, CPU Usage tool, hot path highlighting |
perf + perfcollect on Linux |
Native frames and kernel time too |
An order-search API ran at 70% CPU on four instances. A 60-second trace under load showed 31% of samples under System.Text.Json serialising a 400-field entity the client never used, and 12% exclusive in Enumerable.Contains over a List<int>. Projecting to a 12-field DTO and switching to a HashSet<int> cut CPU to 35%, and the next trace showed both frames under 3%.
Checks that the candidate can capture a CPU profile and correctly interpret it, not just name the tool.
Green flags
Red flags
every ~1 ms
│
▼
SampleProfiler suspends managed threads ──▶ walks each stack ──▶ writes a sample event
│ (thread id, frames)
└── resumes threads
thousands of samples ──▶ aggregated by identical stack ──▶ call tree / flame graph
It is statistical: with 1 ms sampling, 60 seconds and 20 busy threads you get about a million samples, which is plenty for anything above 1%. Short, rare events are under-represented; use event-based tracing for those.
EventPipe's sample profiler records managed threads whether they are running or waiting, so its tree is closer to wall-clock (thread) time. Tools differ:
BLOCKED_TIME only with ETW/kernel data on Windows; with EventPipe you recognise waits by method names (Monitor.Enter, SemaphoreSlim.Wait, Task.Wait, socket receive).perf (via perfcollect) gives real on-CPU samples including native and kernel frames.Async code adds a twist: an awaiting request has no thread, so time spent awaiting I/O doesn't appear at all. For async latency, use distributed traces (Application Insights, OpenTelemetry) and dotnet-trace's activity events, not CPU samples.
| Kestrel request (100%) |
| OrderController.Search (82%) | Logging 9% |
| OrderService.Find (35%) | JsonSerializer.Serialize (41%) |
| EF query (20%) | List.Contains 12% | WriteProperties ... (38%) |
[MethodImpl(MethodImplOptions.NoInlining)]).list.Contains in a loop, load it with k6, and capture dotnet-trace collect -n App --duration 00:00:30 --format speedscope. Find the frame in speedscope.app.Task.Delay(100).Wait() and see how it looks in the samples compared with real CPU work.Capturing a CPU profile from a running service and a container, and the kind of fix a profile typically leads to.
# Local or VM: 60 s of CPU samples once the service is warm and under load
dotnet-trace collect -n Search.Api --profile cpu-sampling \
--duration 00:01:00 -o search.nettrace
# View in a browser on any OS
dotnet-trace convert search.nettrace --format speedscope # open in speedscope.app
# Kubernetes: run the tool inside the pod (or use dotnet-monitor's /trace endpoint)
kubectl exec -it search-api-7d9f -- /tools/dotnet-trace collect -p 1 --duration 00:00:30
kubectl cp search-api-7d9f:/app/trace.nettrace ./trace.nettrace
The profile showed Regex..ctor and List<int>.Contains as wide self-time frames. Before and after:
using System.Text.RegularExpressions;
namespace Search.Api;
public sealed partial class SkuFilter
{
// BEFORE (hot in the profile): new Regex per call, O(n) Contains per item
// public bool IsAllowed(string sku, List<int> blockedIds) =>
// new Regex(@"^[A-Z]{3}-(\d+)$").Match(sku) is { Success: true } m
// && !blockedIds.Contains(int.Parse(m.Groups[1].Value));
// AFTER: source-generated regex built once at compile time,
// O(1) lookups in a FrozenSet built at start-up.
[GeneratedRegex(@"^[A-Z]{3}-(\d+)$")]
private static partial Regex SkuPattern();
private readonly System.Collections.Frozen.FrozenSet<int> _blocked;
public SkuFilter(IEnumerable<int> blockedIds) =>
_blocked = System.Collections.Frozen.FrozenSet.ToFrozenSet(blockedIds);
public bool IsAllowed(string sku) =>
SkuPattern().Match(sku) is { Success: true } m
&& !_blocked.Contains(int.Parse(m.Groups[1].ValueSpan));
}
CPU profiles answer 'where does CPU go?', which is only one of the questions behind 'it's slow'. I decide which question I have first, from the symptom, and pick the tool to match. Mixing these up is how teams spend a week optimising serialisation when the real cost was a lock. I also keep the evidence: the before and after traces and the CPU-per-request metric go in the PR, so reviewers can see the change did what it claimed.
| Symptom | Tool | Why |
|---|---|---|
| High CPU per request | dotnet-trace cpu-sampling | Shows the hot managed code |
| Low CPU, high latency, threads rising | Contention events, ThreadPool counters, dump of stacks | The time is waiting, not computing |
| Slow async I/O calls | Application Insights / OpenTelemetry traces | Awaits hold no thread, so samples miss them |
| High CPU in native or kernel code | perf via perfcollect (Linux) |
Sees native and kernel frames |
| Memory growth | dotnet-gcdump | A CPU profile can't show retention |
| Approach | When it fits | Cost | When not to |
|---|---|---|---|
| dotnet-trace sampling | High CPU, hot code paths | Few % CPU, 100s of MB files | Async I/O latency |
perf / perfcollect (Linux) |
Native, kernel or JIT-generated code | Needs perf installed and permissions | Quick managed-only checks |
| Visual Studio profiler | Local repro, rich UI | Needs a dev machine or the trace file | Production containers directly |
| Application Insights Profiler | Always-on sampled traces tied to requests | Agent and data residency review | Detailed one-off investigations |
The .NET diagnostics tools all talk to the runtime over its diagnostics IPC channel, so they work on Windows, Linux and in containers without a debugger.
I start with counters because they are cheap, then pick the heavier tool the symptom points to. The trade-off is overhead and data sensitivity: a full dump contains every secret in memory.
Throughput that plateaus with spare CPU points at threads waiting, not working. I confirm with dotnet-counters: monitor-lock-contention-count (the dotnet.monitor.lock_contentions metric) climbing with load. Then I find which lock with dotnet-trace using the contention events (--clrevents contention), which record the waiting stack and duration, or a dotnet-dump where clrstack -all shows dozens of threads in Monitor.Enter on the same object.
Fixes, in order: shrink the critical section and never hold a lock across I/O; replace it with ConcurrentDictionary, Interlocked or an immutable snapshot swapped atomically; or shard the lock per key. Then I verify with the same load test. The trade-off: lock-free designs are harder to get right, so I take the simplest one that removes the contention.
First I measure: Application Insights tells me which endpoint is slow and at what percentile, and whether time goes into dependencies like SQL or HTTP. Then I reproduce it on a Release build and run the Visual Studio Performance Profiler (Alt+F2): CPU Usage for hot paths, Database for query count and duration, .NET Object Allocation Tracking for GC pressure, and .NET Async for slow awaits. In an environment where I can't use Visual Studio, dotnet-counters shows live metrics like thread pool queue length and GC, and dotnet-trace captures CPU samples. I fix the biggest cause, often an N+1 query, re-measure against the baseline, and add a load test so it doesn't regress.
How to tell it (STAR)
**S:** At [company] our search API was running at [75%] CPU at peak and we were about to double the instance count. **T:** I wanted to know where the CPU actually went before we paid for more servers. **A:** I captured a 60-second dotnet-trace under peak load and read it bottom-up in PerfView. Two frames stood out: a Regex built on every call and a List.Contains inside a loop, together about [36%] of samples. I replaced them with a source-generated regex and a FrozenSet, proved it with BenchmarkDotNet, and re-profiled after release. **R:** CPU dropped to [38%], p95 fell from [420 ms] to [240 ms], and we cancelled the scale-out, saving about [$X a month].
Last updated 23 Nov 2026.