Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

How to profile lines of code in script

Discussion in 'Scripting' started by RakNet, Oct 8, 2016.

  1. RakNet

    RakNet

    Joined:
    Oct 9, 2013
    Posts:
    313
    You would think this is very common but I can't find out how to profile how long particular blocks of code take to execute.

    I tried
    int start = System.Environment.TickCount;
    DoSomething();
    int end = System.Environment.TickCount;
    tine time - start - end;

    However, while the function actually took a minute the returned value was like 3000, which I assume means 3 seconds.

    I also tried Profiler.BeginSample, however the sample did not show up or else I can't find it - this is code that only runs one time when I press a button.

    This is in editor mode, not play mode.
     
  2. MathiasDG

    MathiasDG

    Joined:
    Jul 1, 2014
    Posts:
    114
    Code (CSharp):
    1. System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
    2. sw.Start();
    3. //  Run code
    4. sw.Stop();
    5. double elapsedMilliseconds = sw.Elapsed.TotalMilliseconds;
     
  3. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    I would run with Profiler.BeginSample and Profiler.EndSample. You then have to run the project with the profiler attatched.

    Most of the time in well structured code you don't actually need to put on the sample calls, the profiler will do it well enough just based on the method calls.