Created
March 27, 2023 08:43
-
-
Save Arlorean/dbc6243b052edcc027331ab653ab13d2 to your computer and use it in GitHub Desktop.
Profile a block of C# code in Unity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.IO; | |
using System.Runtime.CompilerServices; | |
using UnityEngine; | |
/// <summary> | |
/// Log the time taken to execute a block of code to the Unity console.<br/> | |
/// <example> | |
/// Here is an example of how to use it in a script.<br/> | |
/// The result is the total time taken to execute <c>CallMyMethod()</c> and <c>CallAnotherMethod()</c>. | |
/// <code> | |
/// // SomeClass.cs | |
/// void SomeMethod() { | |
/// ... | |
/// using (new Profile("MyCodeSection")) { | |
/// CallMyMethod(); | |
/// CallAnotherMethod(); | |
/// } | |
/// .... | |
/// } | |
/// </code> | |
/// | |
/// This would result in something like this being output to the console: | |
/// <code> | |
/// MyCodeSection: SomeMethod (SomeClass.cs:181) - 1.325553s | |
/// </code> | |
/// </example> | |
/// </summary> | |
public class Profile : IDisposable | |
{ | |
string description; | |
string memberName; | |
string sourceFilePath; | |
int sourceLineNumber; | |
float startTime; | |
public Profile(string description = "", [CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0) { | |
this.description = description; | |
this.memberName = memberName; | |
this.sourceFilePath = sourceFilePath; | |
this.sourceLineNumber = sourceLineNumber; | |
startTime = Time.realtimeSinceStartup; | |
} | |
public void Dispose() { | |
var endTime = Time.realtimeSinceStartup; | |
sourceFilePath = Path.GetFileName(sourceFilePath); | |
Debug.Log($"{description}: {memberName} ({sourceFilePath}:{sourceLineNumber}) - {endTime - startTime}s"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment