暂无描述
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

GcAllocRecorderTest.cs 2.6KB

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