67544bae599fddcc0774933c4cbc133c3a6f9ffc
[platform/upstream/coreclr.git] / tests / src / JIT / Performance / CodeQuality / BenchI / CSieve / CSieve.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 // Based on Eratosthenes Sieve Prime Number Program in C, Byte Magazine, January 1983.
6
7 using Microsoft.Xunit.Performance;
8 using System;
9 using System.Runtime.CompilerServices;
10 using Xunit;
11
12 [assembly: OptimizeForBenchmarks]
13
14 namespace Benchstone.BenchI
15 {
16 public static class CSieve
17 {
18
19 #if DEBUG
20     public const int Iterations = 1;
21 #else
22     public const int Iterations = 200;
23 #endif
24
25     const int Size = 8190;
26
27     [MethodImpl(MethodImplOptions.NoInlining)]
28     static bool Bench() {
29         bool[] flags = new bool[Size + 1];
30         int count = 0;
31         for (int iter = 1; iter <= Iterations; iter++)
32         {
33             count = 0;
34
35             // Initially, assume all are prime
36             for (int i = 0; i <= Size; i++)
37             {
38                 flags[i] = true;
39             }
40
41             // Refine
42             for (int i = 2; i <= Size; i++)
43             {
44                 if (flags[i])
45                 {
46                     // Found a prime
47                     for (int k = i + i; k <= Size; k += i)
48                     {
49                         // Cancel its multiples
50                         flags[k] = false;
51                     }
52                     count++;
53                 }
54             }
55         }
56
57         return (count == 1027);
58     }
59
60     [Benchmark]
61     public static void Test() {
62         foreach (var iteration in Benchmark.Iterations) {
63             using (iteration.StartMeasurement()) {
64                 for (int i = 0; i < Iterations; i++) {
65                     Bench();
66                 }
67             }
68         }
69     }
70
71     static bool TestBase() {
72         bool result = true;
73         for (int i = 0; i < Iterations; i++) {
74             result &= Bench();
75         }
76         return result;
77     }
78
79     public static int Main() {
80         bool result = TestBase();
81         return (result ? 100 : -1);
82     }
83 }
84 }