-
Notifications
You must be signed in to change notification settings - Fork 209
/
Copy pathfibonacci-with-yields.cs
55 lines (44 loc) · 1.25 KB
/
fibonacci-with-yields.cs
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Diagnostics;
using Xunit;
public class Async2FibonacciWithYields
{
const int iterations = 3;
const bool doYields = true;
[Fact]
public static void Test()
{
long allocated = GC.GetTotalAllocatedBytes(precise: true);
AsyncEntry().GetAwaiter().GetResult();
allocated = GC.GetTotalAllocatedBytes(precise: true) - allocated;
System.Console.WriteLine("allocated: " + allocated);
}
public static async Task AsyncEntry()
{
for (int i = 0; i < iterations; i++)
{
var sw = Stopwatch.StartNew();
int result = await Fib(25);
sw.Stop();
Console.WriteLine($"{sw.ElapsedMilliseconds} ms result={result}");
}
}
static async Task<int> Fib(int i)
{
if (i <= 1)
{
if (doYields)
{
await Task.Yield();
}
return 1;
}
int i1 = await Fib(i - 1);
int i2 = await Fib(i - 2);
return i1 + i2;
}
}