Course contentsShow
← Unity Game Development
Lesson 145 of 8282. Scripting and LifecycleFree lesson

Measuring Method Execution Time with Profiler Samples

Use the Profiler.BeginSample and EndSample API to wrap specific code blocks and measure their precise performance impact during gameplay execution.

In this lesson, you will learn how to isolate and measure the exact execution time of specific code blocks using the Profiler.BeginSample and Profiler.EndSample API.

When you look at the Unity Profiler, it often shows you how much time an entire method like Update() takes, but it doesn't tell you which specific lines inside that method are the slowest. By manually adding "Profiler Samples," you can place custom markers around any section of your code to see its performance footprint in the Profiler window under the CPU Usage module.

How to Implement Sampling

To measure a specific task, you wrap your code between these two commands:

using UnityEngine.Profiling; // 1. Don't forget this namespace!

void Update()
{
    // Start measuring
    Profiler.BeginSample("MyExpensiveCalculation");

    // The code you want to test
    PerformComplexMath();

    // Stop measuring
    Profiler.EndSample();
}

When you run your game in the Editor and open the Profiler (Window > Analysis > Profiler), look for the "CPU Usage" timeline. You will see a custom entry labeled "MyExpensiveCalculation." By clicking on it, the Profiler will show you exactly how many milliseconds that block took to execute.

Important Considerations

  • Pairing is Mandatory: Every BeginSample must be paired with an EndSample. If you create a logic branch (like an if statement) that skips the EndSample, your profiler data will become corrupted until the next frame.
  • Performance Overhead: While these samples are fast, you should avoid placing them inside extremely high-frequency loops (like processing 10,000 items every frame) as the overhead of the sampling system itself can begin to skew your performance data.
  • Editor Only: These samples are automatically stripped from "Release" builds, meaning they won't impact your final game's performance for players—they are purely for your own analysis during development.

Using these samples allows you to stop guessing which parts of your scripts are slowing down your game and start making data-driven optimization decisions.

Key Takeaway: Use Profiler.BeginSample and Profiler.EndSample to create custom markers in the Profiler that allow you to isolate and track the precise execution time of specific code blocks.