A game about forced loneliness, made by TACStudios
1using System; 2using System.Diagnostics; 3using System.Diagnostics.CodeAnalysis; 4using System.Threading; 5using Unity.Collections.LowLevel.Unsafe; 6 7namespace UnityEditor.Rendering 8{ 9 /// <summary> 10 /// Allows time measurements 11 /// </summary> 12 /// <example> 13 /// double duration = 0; 14 /// using (TimedScope.FromPtr(&amp;duration)) 15 /// { 16 /// // something to get the time 17 /// } 18 /// Debug.Log($"Duration: {duration}") 19 /// </example> 20 public unsafe struct TimedScope : IDisposable 21 { 22 static readonly ThreadLocal<Stopwatch> s_StopWatch = new ThreadLocal<Stopwatch>(() => new Stopwatch()); 23 24 double* m_DurationMsPtr; 25 26 TimedScope(double* durationMsPtr) 27 { 28 m_DurationMsPtr = durationMsPtr; 29 s_StopWatch.Value.Start(); 30 } 31 32 /// <summary> 33 /// Dispose method to retrieve the time 34 /// </summary> 35 void IDisposable.Dispose() 36 { 37 s_StopWatch.Value.Stop(); 38 *m_DurationMsPtr = s_StopWatch.Value.Elapsed.TotalMilliseconds; 39 s_StopWatch.Value.Reset(); 40 } 41 42 /// <summary> 43 /// Obtains a <see cref="TimedScope"/>. 44 /// 45 /// Safety: <paramref name="durationMsPtr"/> must be a non-null pointer to a valid memory location for a double. 46 /// </summary> 47 /// <param name="durationMsPtr">The location to write the duration in milliseconds to.</param> 48 /// <returns>A <see cref="TimedScope"/></returns> 49 public static unsafe TimedScope FromPtr([DisallowNull] double* durationMsPtr) 50 { 51 return new TimedScope(durationMsPtr); 52 } 53 54 /// <summary> 55 /// Obtains a <see cref="TimedScope"/> 56 /// </summary> 57 /// <param name="durationMs">The location to write the duration in milliseconds to.</param> 58 /// <returns>A <see cref="TimedScope"/></returns> 59 public static TimedScope FromRef(ref double durationMs) 60 { 61 return new TimedScope((double*)UnsafeUtility.AddressOf(ref durationMs)); 62 } 63 } 64}