ARTICLE AD BOX
I've been profiling my code in Unity using UnityEngine.Profiling and it has been very helpful - making me easily able to determine what parts of my code take the longest time to execute.
When using Profiler.BeginSample the sample is recorded until the next Profiler.EndSample call is reached. Most of the time, this is fine, but there's an edge case where I find how this works a little annoying. Take this simple example:
bool NumberIsEven(int x) { Profiler.BeginSample("NumberIsEven"); if (x % 2 == 0) { Profiler.EndSample(); return true; } Profiler.EndSample(); return false; }Here, I've had to use Profiler.EndSample() twice as we have two possible places where the function can hit a return. This is not so bad of course, but imagine instead a function where we have several different places where we can hit a return statement - perhaps something involving a massive switch statement for example. Putting Profiler.EndSample() just before each and every one of them is pretty annoying.
I wonder instead if it is possible to somehow tie a sample to a method that we are currently in, avoiding the need for multiple Profiler.EndSample() statements. For example, I want something like this:
//This code is functionally identical to the above example. bool NumberIsEven(int x) { TieSampleToCurrentMethod("NumberIsEven"); //Begins a profiler sample tied to this function which will end whenever this function is exited if (x % 2 == 0) { return true; //Profiler sample automatically ends when we hit this } return false; //Profiler sample automatically ends when we hit this }Can I do this? If so, how?
