S&box Wiki

Revision Difference

Performance_Profiling#549778

<cat>Code.Misc</cat>⤶ <title>CPU Performance Profiling</title>⤶ ⤶ # CPU Performance Profiling⤶ ⤶ Code profiling tools allow you to analyse the execution of your code during runtime and find any performance bottlenecks.⤶ ⤶ This tutorial will use the profiling tools in Microsoft Visual Studio, but there is lots of other software that does the same thing.⤶ ⤶ ## Instructions⤶ ⤶ 1. Open up Microsoft Visual Studio.⤶ ⤶ 2. Open up your gamemode in the game client or editor. The advantage of using the game client is that you avoid the overhead of the editor, which can make the execution analysis more accurate. Whether that matters much in practice though is debatable.⤶ ⤶ 3. Go to `Debug` -> `Attach to Process...`.⤶ ⤶ <upload src="b0cef/8db4dbbedc4c395.png" size="11536" name="image.png" />⤶ ⤶ 4. Find sbox.exe or sbox-dev.exe in the process list and press `Attach`.⤶ ⤶ <upload src="b0cef/8db4dbc14c9b59f.png" size="53063" name="image.png" />⤶ ⤶ 5. In this menu that should pop up go to `CPU Usage`. You'll also want to press `Enable CPU profiling to see a breakdown of CPU usage by function`.⤶ ⤶ <upload src="b0cef/8db4dbc6f9f07ae.png" size="9145" name="image.png" />⤶ ⤶ 6. Go back to your gamemode and do random stuff for about a minute or so. The longer you profile it for, the more accurate your results will be (but anything over 60 seconds is probably overkill). If there's something in particular you want to benchmark, then just spam that over and over again in-game.⤶ ⤶ 7. When you are done, break all.⤶ ⤶ <upload src="b0cef/8db4dbcd49ac3d0.png" size="2755" name="image.png" /> ⤶ ⤶ 8. It will do some stuff, be patient. Your game will be frozen now.⤶ ⤶ 9. Click on `Sandbox.Program.Main()`.⤶ ⤶ <upload src="b0cef/8db4dbcfbd8e1b8.png" size="7377" name="image.png" />⤶ ⤶ 10. Switch to `Call Tree` since it is probably the nicest way to view what's going on.⤶ ⤶ <upload src="b0cef/8db4dbd08c16848.png" size="10734" name="image.png" />⤶ ⤶ 11. Expand `Sandbox.Program.Main()`.⤶ ⤶ <upload src="b0cef/8db4dbd3221319b.png" size="50496" name="image.png" />⤶ ⤶ 12. This will basically show you the slowest functions that were called and how much total CPU time they took up. Main() is the starting point for your program, so that will always be high. However, we can see that NPCCar.Tick() is taking up 2.14% of our CPU time, which is quite a lot. We can navigate deeper into the tree to find out the cause.⤶ ⤶ <upload src="b0cef/8db4dbd8aaa09d5.png" size="51657" name="image.png" />⤶ ⤶ 13. In this case the culprit was the function CarWheel.Raycast() making too many raycasts. Every car wheel is making a raycast every tick, and we have have 21 cars in the map, each with 4 wheels, totalling 5040 raycasts per tick! Oops!⤶ ⤶ 14. Press `Continue` or `Stop Debugging` to unfreeze the game.⤶ ⤶ <upload src="b0cef/8db4dbdf803985f.png" size="5952" name="image.png" />