5dda2631b227c1b67af27621fd65f5de3e934bc7
[platform/upstream/coreclr.git] / tests / src / JIT / Performance / CodeQuality / BenchI / Permutate / Permutate.cs
1 // Licensed to the .NET Foundation under one or more agreements.
2 // The .NET Foundation licenses this file to you under the MIT license.
3 // See the LICENSE file in the project root for more information.
4 //
5
6 using Microsoft.Xunit.Performance;
7 using System;
8 using System.Runtime.CompilerServices;
9 using Xunit;
10
11 [assembly: OptimizeForBenchmarks]
12
13 namespace Benchstone.BenchI
14 {
15 public class Permutate
16 {
17 #if DEBUG
18     public const int Iterations = 1;
19 #else
20     public const int Iterations = 20000;
21 #endif
22
23     private int[] _permArray = new int[11];
24     private static int s_pctr;
25
26     private static
27     void Swap(int[] arr, int i, int j)
28     {
29         int t = arr[i];
30         arr[i] = arr[j];
31         arr[j] = t;
32     }
33
34     private void Initialize()
35     {
36         for (int i = 1; i <= 7; i++)
37         {
38             _permArray[i] = i - 1;
39         }
40     }
41
42     private void PermuteArray(int n)
43     {
44         int k;
45         s_pctr = s_pctr + 1;
46         if (n != 1)
47         {
48             PermuteArray(n - 1);
49             for (k = n - 1; k >= 1; k--)
50             {
51                 Swap(_permArray, n, k);
52                 PermuteArray(n - 1);
53                 Swap(_permArray, n, k);
54             }
55         }
56     }
57
58     private bool Validate()
59     {
60         int k = 0;
61
62         for (int i = 0; i <= 6; i++)
63         {
64             for (int j = 1; j <= 7; j++)
65             {
66                 if (_permArray[j] == i)
67                 {
68                     k = k + 1;
69                 }
70             }
71         }
72
73         return (k == 7);
74     }
75
76     [MethodImpl(MethodImplOptions.NoInlining)]
77     private bool Bench()
78     {
79         Initialize();
80
81         for (int i = 0; i < Iterations; ++i)
82         {
83             s_pctr = 0;
84             PermuteArray(7);
85         }
86
87         bool result = Validate();
88
89         return result;
90     }
91
92     [Benchmark]
93     public static void Test()
94     {
95         Permutate P = new Permutate();
96         foreach (var iteration in Benchmark.Iterations)
97         {
98             using (iteration.StartMeasurement())
99             {
100                 P.Bench();
101             }
102         }
103     }
104
105     private static bool TestBase()
106     {
107         Permutate P = new Permutate();
108         bool result = P.Bench();
109         return result;
110     }
111
112     public static int Main()
113     {
114         bool result = TestBase();
115         return (result ? 100 : -1);
116     }
117 }
118 }