Skip to content

Instantly share code, notes, and snippets.

@Arlorean
Created March 27, 2023 08:43
Show Gist options
  • Save Arlorean/dbc6243b052edcc027331ab653ab13d2 to your computer and use it in GitHub Desktop.
Save Arlorean/dbc6243b052edcc027331ab653ab13d2 to your computer and use it in GitHub Desktop.
Profile a block of C# code in Unity
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