Advertisement
napland

TestMagnitude

Oct 3rd, 2016
291
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.78 KB | None | 0 0
  1. // Make sure to use this in your namespace declarations
  2. using System.Diagnostics;
  3. // This is needed because System.Diagnostics also contains a Debug class
  4. using Debug = UnityEngine.Debug;
  5.  
  6. // We'll need a lot of iterations to get any result for this.
  7. public int iterations = 1000000;
  8.  
  9. void TestMagnitude()
  10. {
  11.     // Fill up an array of vectors to test on.
  12.     Vector3[] testVectors = new Vector3[iterations];
  13.     for (int i = 0; i < iterations; i++)
  14.     {
  15.         testVectors[i] =
  16.             new Vector3(
  17.                 Random.Range(-100, 100),
  18.                 Random.Range(-100, 100),
  19.                 Random.Range(-100, 100));
  20.     }
  21.  
  22.     // Instantiate a new stopwatch
  23.     Stopwatch stopwatch = new Stopwatch();
  24.  
  25.     // Set up our value outside of the for loop just in case there's any
  26.     // performance hit from declaring it inside the loop.
  27.     float value;
  28.  
  29.     // Test sqrMagnitude on our test vectors
  30.     stopwatch.Start();
  31.     for (int i = 0; i < iterations; i++)
  32.     {
  33.         value = testVectors[i].sqrMagnitude;
  34.     }
  35.     stopwatch.Stop();
  36.  
  37.     // "Save" the total test time in a variable to output later.
  38.     double sqrMagnitudeTime = stopwatch.ElapsedMilliseconds;
  39.     // Make sure to reset/clear the stopwatch befor using it again.
  40.     stopwatch.Reset();
  41.  
  42.     // Test magnitude on our test vectors
  43.     stopwatch.Start();
  44.     for (int i = 0; i < iterations; i++)
  45.     {
  46.         value = testVectors[i].magnitude;
  47.     }
  48.     stopwatch.Stop();
  49.  
  50.     double magnitudeTime = stopwatch.ElapsedMilliseconds;
  51.     stopwatch.Reset();
  52.  
  53.     // Output the test results to the console.
  54.     Debug.LogFormat(
  55.         "Magnitude test results:\n" +
  56.         "total sqrMagnitude time: {0:G}ms\n" +
  57.         "average sqrMagnitude time: {1:G}ms\n" +
  58.         "total magnitude time: {2:G}ms\n" +
  59.         "average magnitude time: {3:G}ms\n",
  60.         sqrMagnitudeTime,
  61.         (sqrMagnitudeTime / iterations),
  62.         magnitudeTime,
  63.         (magnitudeTime / iterations)
  64.         );
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement