blob: 3c79a89edc8ebeb909b914c7682b99880ae36cf9 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/* The Computer Language Benchmarks Game
* http://benchmarksgame.alioth.debian.org/
*
* Port of the C code that uses GMP
* Just switched it to use C#'s BigInteger instead
*
* To compile use csc /o+ /r:System.Numerics.dll
*
* modified for use with xunit-performance
*/
using Microsoft.Xunit.Performance;
using System;
using System.Numerics;
using System.Text;
[assembly: OptimizeForBenchmarks]
namespace BenchmarksGame
{
public class pidigits
{
#if DEBUG
public const int Iterations = 1;
#else
public const int Iterations = 50;
#endif
private BigInteger _acc,_den,_num;
public pidigits()
{
_acc = BigInteger.Zero;
_den = BigInteger.One;
_num = BigInteger.One;
}
public uint extract_digit(uint nth)
{
return (uint)((_num * nth + _acc) / _den);
}
public void eliminate_digit(uint d)
{
_acc -= _den * d;
_acc *= 10;
_num *= 10;
}
public void next_term(uint k)
{
uint k2 = k * 2 + 1;
_acc += _num * 2;
_acc *= k2;
_den *= k2;
_num *= k;
}
public void Calculate(int n, bool verbose = false)
{
StringBuilder sb = new StringBuilder(20);
uint d, k, i;
for (i = k = 0; i < n;)
{
next_term(++k);
if (_num > _acc)
continue;
d = extract_digit(3);
if (d != extract_digit(4))
continue;
sb.Append((char)('0' + d));
if (++i % 10 == 0)
{
if (verbose)
{
Console.WriteLine("{0}\t:{1}", sb, i);
}
sb.Clear();
}
eliminate_digit(d);
}
}
public static int Main(String[] args)
{
int length = args.Length == 0 ? 10 : Int32.Parse(args[0]);
for (int i = 0; i < Iterations; i++)
{
pidigits p = new pidigits();
p.Calculate(length, true);
}
return 100;
}
[Benchmark]
public static void Bench()
{
int length = 600;
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < Iterations; i++)
{
pidigits p = new pidigits();
p.Calculate(length);
}
}
}
}
}
}
|