Home > Back-end >  How to use Profiler to profile a Start() function in Unity
How to use Profiler to profile a Start() function in Unity

Time:12-18

When I useProfiler.BeginSample("Update Example") and Profiler.EndSample() in Update(), I can see "Update Example" in Update.ScriptRunBehaviorUpdate in the profiler window.

But when I use Profiler..."Start Example"... in Start(), I cannot see or find any mention in the profiler. Is there any way to track code in Start()?

using UnityEngine;
using UnityEngine.Profiling;
public class Example : MonoBehaviour
{
    BoxParameter bParameter;
    // Start is called before the first frame update
    void Start()
    {
        Profiler.BeginSample("Start Example");
        bParameter = GameObject.Find("Main Camera").GetComponent<ZombieInventory>().box;
        Debug.Log(bParameter.width);
        Profiler.EndSample();
    }
    // Update is called once per frame
    void Update()
    {
        Profiler.BeginSample("Update Example");
        bParameter = GameObject.Find("Main Camera").GetComponent<ZombieInventory>().box;
        Debug.Log(bParameter.width);
        Profiler.EndSample();
    }

CodePudding user response:

Play with Clear on Play and Deep Profile turned on.

enter image description here

Moves to 1Frame after playback. It is easier to step using a controller.

enter image description here

Then you can check the following.

enter image description here

To see if you get a value, try searching for the script name in the search window. It will not give you the details, but you can check if the value is taken.

enter image description here

The following test code was used.


using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Profiling;

public class ProfilingTest : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        Profiler.BeginSample("Start Example");
        var list = new List<int>();
        for (var i = 0; i < 2000000;   i)
        {
            list.Add(i);
        }
        Profiler.EndSample();
    }
    // Update is called once per frame
    void Update()
    {
        Profiler.BeginSample("Update Example");
        var list = new List<int>();
        for (var i = 0; i < 2000000;   i)
        {
            list.Add(i);
        }
        Profiler.EndSample();
    }
}

BTW: Maybe it is because it is test code, but the Find function is heavy and should not be used. caching Camera.main is the fastest way. the same goes for GetComponent.

Camera _camera;

void Start()
{
    _camera = Camera.main;
}
  • Related