Search Unity

Want to build a methos call tracer and I was thinking I can user the profiler API?

Discussion in 'Scripting' started by esteban16108, Jun 8, 2021.

  1. esteban16108

    esteban16108

    Joined:
    Jan 23, 2014
    Posts:
    159
    Hi,

    Working on this legacy project that's kind of convoluted, trying to understand the cross references sometimes gives me headaches.

    So, I was thinking, what if I can make something that can trace all method calls in a run, save in a file and then I render a kind of flowchart?

    I was looking everywhere and didn't found anything, then I remember that the profiler does just that.

    So, my question would be. Is a good approach? Can be done with the profiler API? Or is there something better?

    Cheers!
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    The profiler needs to have things that hook into it to tell it what to display, and Unity's builtin methods all do that, giving it a good base to work from. There's nothing magic about Profiler tracing this stuff. It's a good model for developing this sort of data.

    Basically you must keep track of a "Stack" of code information. The most basic form of what Profiler does would look like:
    Code (csharp):
    1. public static class CodeChunkTracer {
    2.    private static Stack<string> stack = new Stack<string>();
    3.    public static void BeginCodeChunk(string chunkName) {
    4.       stack.Push(chunkName);
    5.       OutputStack();
    6.    }
    7.  
    8.    public static void EndCodeChunk() {
    9.       stack.Pop();
    10.       OutputStack();
    11.    }
    12.  
    13.    public static void OutputStack() {
    14.       string output = "";
    15.       foreach (string s in stack) output += $".{s}";
    16.       Debug.Log(output);
    17.    }
    18. }
    Written hastily and it's been a while since I've used Stack<>, so may not be 100% right, but it shows the general concept. You can do something besides Debug.Log() such as write to a file, and then use that data however you like
     
  3. esteban16108

    esteban16108

    Joined:
    Jan 23, 2014
    Posts:
    159
    Thing is I don't want to go around putting some custom code. As the profiler works in some way to identify all the methods and classes, I would like to piggyback on something like that to log some kind of execution flow.
     
  4. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    No it doesn't. It knows all the Unity-invoked methods (Update, FixedUpdate, etc) because Unity itself calls all those things, but beyond that, it doesn't automatically know about all the other functions that are called. Unless they've added some new feature recently that I don't know about.