No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

GcAllocRecorderTest.cs 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using System;
  2. using NUnit.Framework;
  3. using Unity.Collections.Tests;
  4. internal class GcAllocRecorderTest
  5. {
  6. [Test]
  7. public void TestBeginEnd()
  8. {
  9. GCAllocRecorder.BeginNoGCAlloc();
  10. GCAllocRecorder.EndNoGCAlloc();
  11. }
  12. // NOTE: Causing GC allocation with new requires an unused variable
  13. #pragma warning disable 219
  14. [Test]
  15. public void TestNoAlloc()
  16. {
  17. GCAllocRecorder.ValidateNoGCAllocs(() =>
  18. {
  19. var p = new int();
  20. });
  21. }
  22. [Test]
  23. public void TestAlloc()
  24. {
  25. Assert.Throws<AssertionException>(() =>
  26. {
  27. GCAllocRecorder.ValidateNoGCAllocs(() =>
  28. {
  29. var p = new int[5];
  30. });
  31. });
  32. }
  33. #pragma warning restore 219
  34. }
  35. namespace Unity.Collections.Tests
  36. {
  37. internal static class GCAllocRecorder
  38. {
  39. static UnityEngine.Profiling.Recorder AllocRecorder;
  40. static GCAllocRecorder()
  41. {
  42. AllocRecorder = UnityEngine.Profiling.Recorder.Get("GC.Alloc");
  43. }
  44. public static int CountGCAllocs(Action action)
  45. {
  46. AllocRecorder.FilterToCurrentThread();
  47. AllocRecorder.enabled = false;
  48. AllocRecorder.enabled = true;
  49. action();
  50. AllocRecorder.enabled = false;
  51. return AllocRecorder.sampleBlockCount;
  52. }
  53. // NOTE: action is called twice to warmup any GC allocs that can happen due to static constructors etc.
  54. public static void ValidateNoGCAllocs(Action action)
  55. {
  56. // warmup
  57. CountGCAllocs(action);
  58. // actual test
  59. var count = CountGCAllocs(action);
  60. if (count != 0)
  61. throw new AssertionException($"Expected 0 GC allocations but there were {count}");
  62. }
  63. public static void BeginNoGCAlloc()
  64. {
  65. AllocRecorder.FilterToCurrentThread();
  66. AllocRecorder.enabled = false;
  67. AllocRecorder.enabled = true;
  68. }
  69. public static void EndNoGCAlloc()
  70. {
  71. AllocRecorder.enabled = false;
  72. int count = AllocRecorder.sampleBlockCount;
  73. if (count != 0)
  74. throw new AssertionException($"Expected 0 GC allocations but there were {count}");
  75. }
  76. }
  77. }