简体   繁体   中英

Profiling recursive code in C#/Visual Studio

I have some code in C#, using Visual Studio 2019. To simplify, the structure of the code looks like this:

public class Program
{
    private static async Task Main()
    {
        Perft.RunPerft(5);
    }
}

public class Perft
{        
    Board board = new Board();

    public static void RunPerft(int depth)
    {
        if (depth == 0) return 1;

        board.GetAllMoves();

        int _nodes = 0;
        foreach (Move move in board.moves)
        {
            if (board.MakeMove(move))
            {
                _nodes += PerftRun(depth - 1);
                board.UnmakeMove(move);
            }
        }

        return _nodes;
    }       
}

So I have 3 main functions that I want to know the performance of: GetAllMoves, MakeMove, and UnmakeMove. Is there an easy way to see how much time is spent in each of these functions? Maybe something built in in Visual Studio, instead of using stopwatches?

Well, the oldie-but-goody method I would do, and have done many times, is this...

First, wrap a loop around the outer call, so it takes plenty of time, like 10 seconds or more. For example, if you loop it a million times, the number of seconds it takes altogether is the number of microseconds one call takes.

Second, while it is running, manually pause it 10 or 20 times. Each time, record the call stack.

Third, look at the stacks. The fraction of them containing UnmakeMove and each of your other routines is the fraction of time each routine takes. (Roughly. Unless you like decimal places, roughly is usually good enough.) That fraction, divided by the number of times the routine is called, times the number of microseconds of one overall call is the microseconds of that routine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM