-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdotnet-10-vs-java
More file actions
377 lines (326 loc) · 12.7 KB
/
dotnet-10-vs-java
File metadata and controls
377 lines (326 loc) · 12.7 KB
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Numerics;
using System.Runtime.CompilerServices;
using Sdcb.Arithmetic.Gmp;
sealed class SplitMix64
{
private ulong _x;
public SplitMix64(ulong seed) => _x = seed;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ulong NextUInt64()
{
ulong z = (_x += 0x9E3779B97F4A7C15UL);
z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9UL;
z = (z ^ (z >> 27)) * 0x94D049BB133111EBUL;
return z ^ (z >> 31);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void NextBytes(Span<byte> dst)
{
int i = 0;
while (i < dst.Length)
{
ulong v = NextUInt64();
for (int k = 0; k < 8 && i < dst.Length; k++)
dst[i++] = (byte)(v >> (56 - 8 * k));
}
}
}
enum Op { ADD_MOD, MUL_MOD, MODPOW }
record Result(string Impl, int Bits, Op Op, long Ops, double NsPerOp, long Checksum)
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public string ToJson() => string.Create(CultureInfo.InvariantCulture,
$"{{\"lang\":\"{Impl}\",\"bits\":{Bits},\"op\":\"{Op}\",\"ops\":{Ops},\"nsPerOp\":{NsPerOp:F3},\"checksum\":{Checksum}}}");
}
static class BenchUtil
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void MaskToBitSize(Span<byte> buf, int bitSize)
{
int topBit = (bitSize - 1) % 8;
int keepBits = topBit + 1;
int firstMask = keepBits == 8 ? 0xFF : ((1 << keepBits) - 1);
buf[0] &= (byte)firstMask;
buf[0] |= (byte)(1 << topBit);
}
// 移除无用的ToHex方法(优化后不再需要)
}
static class BigIntegerBench
{
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public static BigInteger[] Gen(int bitSize, int count, ulong seed)
{
var rng = new SplitMix64(seed);
int byteLen = (bitSize + 7) / 8;
var arr = new BigInteger[count];
// 复用缓冲区,避免重复创建
var buf = new byte[byteLen];
for (int i = 0; i < count; i++)
{
rng.NextBytes(buf);
BenchUtil.MaskToBitSize(buf, bitSize);
// 直接使用Span避免数组拷贝
arr[i] = new BigInteger(buf.AsSpan(), isUnsigned: true, isBigEndian: true);
}
return arr;
}
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public static BigInteger GenModulus(int bitSize, ulong seed)
{
var rng = new SplitMix64(seed);
int byteLen = (bitSize + 7) / 8;
var buf = new byte[byteLen];
rng.NextBytes(buf);
BenchUtil.MaskToBitSize(buf, bitSize);
buf[^1] |= 1;
return new BigInteger(buf.AsSpan(), isUnsigned: true, isBigEndian: true);
}
[MethodImpl(MethodImplOptions.AggressiveOptimization | MethodImplOptions.AggressiveInlining)]
public static long RunOnce(Op op, BigInteger[] a, BigInteger[] b, BigInteger[] e, BigInteger mod, int outer)
{
BigInteger acc = BigInteger.Zero;
int n = a.Length;
// 提取内层循环,减少分支预测开销
switch (op)
{
case Op.ADD_MOD:
for (int o = 0; o < outer; o++)
{
for (int i = 0; i < n; i++)
{
acc ^= BigInteger.ModPow(a[i] + b[i], 1, mod);
}
}
break;
case Op.MUL_MOD:
for (int o = 0; o < outer; o++)
{
for (int i = 0; i < n; i++)
{
acc ^= BigInteger.ModPow(a[i] * b[i], 1, mod);
}
}
break;
case Op.MODPOW:
for (int o = 0; o < outer; o++)
{
for (int i = 0; i < n; i++)
{
acc ^= BigInteger.ModPow(a[i], e[i], mod);
}
}
break;
}
return (long)(acc & long.MaxValue);
}
}
static class GmpIntegerBench
{
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public static GmpInteger[] Gen(int bitSize, int count, ulong seed)
{
var rng = new SplitMix64(seed);
int byteLen = (bitSize + 7) / 8;
var arr = new GmpInteger[count];
var buf = new byte[byteLen];
for (int i = 0; i < count; i++)
{
rng.NextBytes(buf);
BenchUtil.MaskToBitSize(buf, bitSize);
// 优化:直接从字节数组构造GmpInteger,避免Hex字符串转换(性能提升核心点)
arr[i] = new GmpInteger(buf, isBigEndian: true);
arr[i].AbsInplace(); // 确保无符号
}
return arr;
}
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public static GmpInteger GenModulus(int bitSize, ulong seed)
{
var rng = new SplitMix64(seed);
int byteLen = (bitSize + 7) / 8;
var buf = new byte[byteLen];
rng.NextBytes(buf);
BenchUtil.MaskToBitSize(buf, bitSize);
buf[^1] |= 1;
var mod = new GmpInteger(buf, isBigEndian: true);
mod.AbsInplace();
return mod;
}
[MethodImpl(MethodImplOptions.AggressiveOptimization | MethodImplOptions.AggressiveInlining)]
public static long RunOnce(Op op, GmpInteger[] a, GmpInteger[] b, GmpInteger[] e, GmpInteger mod, int outer)
{
// 使用using声明自动释放,且复用临时变量
using var acc = GmpInteger.From(0);
using var tmp = GmpInteger.From(0);
int n = a.Length;
// 扁平化循环,减少嵌套层级
int totalIterations = outer * n;
int iter = 0;
switch (op)
{
case Op.ADD_MOD:
while (iter < totalIterations)
{
int i = iter % n;
GmpInteger.AddInplace(tmp, a[i], b[i]);
GmpInteger.ModInplace(tmp, tmp, mod);
GmpInteger.BitwiseXorInplace(acc, acc, tmp);
iter++;
}
break;
case Op.MUL_MOD:
while (iter < totalIterations)
{
int i = iter % n;
GmpInteger.MultiplyInplace(tmp, a[i], b[i]);
GmpInteger.ModInplace(tmp, tmp, mod);
GmpInteger.BitwiseXorInplace(acc, acc, tmp);
iter++;
}
break;
case Op.MODPOW:
while (iter < totalIterations)
{
int i = iter % n;
GmpInteger.PowerModInplace(tmp, a[i], e[i], mod);
GmpInteger.BitwiseXorInplace(acc, acc, tmp);
iter++;
}
break;
}
return acc.GetHashCode();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void DisposeAll(GmpInteger[] xs)
{
if (xs == null) return;
foreach (var x in xs) x?.Dispose();
}
}
static class Runner
{
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
static Result BenchBigInteger(int bits, Op op, BigInteger[] a, BigInteger[] b, BigInteger[] e, BigInteger mod, long targetOps, int warmups, int measures)
{
int n = a.Length;
int outer = (int)Math.Max(1, targetOps / n);
long actualOps = (long)n * outer;
long ck = 0;
// 预热阶段
for (int i = 0; i < warmups; i++)
ck ^= BigIntegerBench.RunOnce(op, a, b, e, mod, outer);
var timesNs = new long[measures];
var sw = new Stopwatch(); // 复用Stopwatch,避免重复创建
for (int i = 0; i < measures; i++)
{
sw.Reset();
sw.Start();
long c = BigIntegerBench.RunOnce(op, a, b, e, mod, outer);
sw.Stop();
ck ^= c;
// 直接计算纳秒,避免重复计算频率
timesNs[i] = sw.ElapsedTicks * (1000000000L / Stopwatch.Frequency);
}
Array.Sort(timesNs);
long median = timesNs[timesNs.Length / 2];
return new Result("csharp_bigint", bits, op, actualOps, (double)median / actualOps, ck);
}
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
static Result BenchGmpInteger(int bits, Op op, GmpInteger[] a, GmpInteger[] b, GmpInteger[] e, GmpInteger mod, long targetOps, int warmups, int measures)
{
int n = a.Length;
int outer = (int)Math.Max(1, targetOps / n);
long actualOps = (long)n * outer;
long ck = 0;
for (int i = 0; i < warmups; i++)
ck ^= GmpIntegerBench.RunOnce(op, a, b, e, mod, outer);
var timesNs = new long[measures];
var sw = new Stopwatch();
for (int i = 0; i < measures; i++)
{
sw.Reset();
sw.Start();
long c = GmpIntegerBench.RunOnce(op, a, b, e, mod, outer);
sw.Stop();
ck ^= c;
timesNs[i] = sw.ElapsedTicks * (1000000000L / Stopwatch.Frequency);
}
Array.Sort(timesNs);
long median = timesNs[timesNs.Length / 2];
return new Result("csharp_gmp_inplace", bits, op, actualOps, (double)median / actualOps, ck);
}
public static int Run(string[] args)
{
bool json = args.Any(a => a == "--json");
const int warmups = 5;
const int measures = 11;
int[] bitSizes = [256, 1024, 4096];
var results = new List<Result>();
// 预计算频率,避免重复计算
long frequency = Stopwatch.Frequency;
GC.TryStartNoGCRegion(1024 * 1024 * 64); // 64MB无GC区域,减少GC干扰
try
{
foreach (int bits in bitSizes)
{
long addOps = bits switch { 256 => 2_000_000L, 1024 => 1_000_000L, _ => 200_000L };
long mulOps = bits switch { 256 => 500_000L, 1024 => 120_000L, _ => 20_000L };
long powOps = bits switch { 256 => 8_000L, 1024 => 1_500L, _ => 250L };
// 预计算种子,避免重复计算
ulong modSeed = 0xA1B2C3D4E5F60708UL ^ (uint)bits;
ulong aSeed = 0x1111222233334444UL ^ (uint)bits;
ulong bSeed = 0x9999AAAABBBBCCCCUL ^ (uint)bits;
ulong apSeed = 0x13579BDF2468ACE0UL ^ (uint)bits;
ulong epSeed = 0x0FEDCBA987654321UL ^ (uint)bits;
// BigInteger data
var modB = BigIntegerBench.GenModulus(bits, modSeed);
var aB = BigIntegerBench.Gen(bits, 1024, aSeed);
var bB = BigIntegerBench.Gen(bits, 1024, bSeed);
var apB = BigIntegerBench.Gen(bits, 256, apSeed);
var epB = BigIntegerBench.Gen(Math.Min(bits, 512), 256, epSeed);
// GmpInteger data (same seeds/bit sizes)
using var modG = GmpIntegerBench.GenModulus(bits, modSeed);
var aG = GmpIntegerBench.Gen(bits, 1024, aSeed);
var bG = GmpIntegerBench.Gen(bits, 1024, bSeed);
var apG = GmpIntegerBench.Gen(bits, 256, apSeed);
var epG = GmpIntegerBench.Gen(Math.Min(bits, 512), 256, epSeed);
try
{
results.Add(BenchBigInteger(bits, Op.ADD_MOD, aB, bB, null!, modB, addOps, warmups, measures));
results.Add(BenchBigInteger(bits, Op.MUL_MOD, aB, bB, null!, modB, mulOps, warmups, measures));
results.Add(BenchBigInteger(bits, Op.MODPOW, apB, null!, epB, modB, powOps, warmups, measures));
results.Add(BenchGmpInteger(bits, Op.ADD_MOD, aG, bG, null!, modG, addOps, warmups, measures));
results.Add(BenchGmpInteger(bits, Op.MUL_MOD, aG, bG, null!, modG, mulOps, warmups, measures));
results.Add(BenchGmpInteger(bits, Op.MODPOW, apG, null!, epG, modG, powOps, warmups, measures));
}
finally
{
GmpIntegerBench.DisposeAll(aG);
GmpIntegerBench.DisposeAll(bG);
GmpIntegerBench.DisposeAll(apG);
GmpIntegerBench.DisposeAll(epG);
}
}
}
finally
{
GC.EndNoGCRegion();
}
if (json)
{
foreach (var r in results) Console.WriteLine(r.ToJson());
}
return 0;
}
}
public static class Program
{
// 启用优化编译
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public static int Main(string[] args) => Runner.Run(args);
}