0Pricing
C# Academy · Lesson

Basic profiling & traces (concepts)

Measure code with Stopwatch, create tiny timing scopes, understand trace correlation IDs, and learn basic micro-benchmark hygiene.

Timing & tracing basics

Aim:

  • Measure hot paths with Stopwatch
  • Add tiny timing scopes for blocks
  • Use trace correlation IDs to link events
  • Avoid noisy measurements

Stopwatch demo

Use Stopwatch to time code; warm up first and repeat the work to smooth out JIT noise.

using System;
using System.Diagnostics;
using System.Threading;

// Simple loop timing with warmup; C# 6 compatible.
public class Program
{
  static int Work(int n)
  {
    int s = 0;
    for (int i = 0; i < n; i++) s += i; // small CPU work
    return s;
  }

  public static void Main(string[] args)
  {
    // Warm up (JIT/caches)
    Work(10000);

    var sw = Stopwatch.StartNew();
    for (int r = 0; r < 10; r++)
    {
      Work(20000);
    }
    sw.Stop();

    Console.WriteLine("Elapsed ms (10 runs): " + sw.ElapsedMilliseconds);
  }
}

All lessons in this course

  1. Logging abstractions, Debug/Trace
  2. Basic profiling & traces (concepts)
  3. Guard & validation patterns
← Back to C# Academy