Last active
December 14, 2015 23:49
-
-
Save GregRos/5168907 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public sealed class CustomRange : IEnumerable<int>,IEnumerator<int> | |
{ | |
private int cur; | |
private readonly int max; | |
public CustomRange(int start, int count) | |
{ | |
cur = start - 1; | |
max = start + count; | |
} | |
public IEnumerator<int> GetEnumerator() | |
{ | |
return this; | |
} | |
public bool MoveNext() | |
{ | |
if (cur < max) | |
{ | |
return false; | |
} | |
cur++; | |
return true; | |
} | |
public void Reset() | |
{ | |
throw new NotImplementedException(); | |
} | |
object IEnumerator.Current | |
{ | |
get | |
{ | |
return Current; | |
} | |
} | |
public int Current | |
{ | |
get | |
{ | |
return cur; | |
} | |
} | |
IEnumerator IEnumerable.GetEnumerator() | |
{ | |
return GetEnumerator(); | |
} | |
public void Dispose() | |
{ | |
} | |
} | |
internal static class Program | |
{ | |
private static void Main(string[] args) | |
{ | |
var range = new CustomRange(0, 100000); | |
var range2 = Enumerable.Range(0, 100000); | |
Bench( | |
() => | |
{ | |
int i = 0; | |
while (i != 100000) | |
{ | |
var y = i; | |
i++; | |
} | |
}, 10); | |
Bench( | |
() => | |
{ | |
foreach (var item in range2) | |
{ | |
var y = item; | |
} | |
}, 10); | |
Bench( | |
() => | |
{ | |
foreach (var item in range) | |
{ | |
var y = item; | |
} | |
}, 10); | |
} | |
private static Stopwatch sw = new Stopwatch(); | |
private static TimeSpan Bench(Action act, int iter) | |
{ | |
for (int i = 0; i < 3; i++) | |
{ | |
act(); | |
} | |
GC.Collect(); | |
Action b = | |
() => | |
{ | |
for (int i = 0; i < iter; i++) | |
{ | |
act(); | |
} | |
}; | |
b(); | |
var thread = new Thread(new ThreadStart(b)); | |
sw.Restart(); | |
thread.Start(); | |
thread.Join(); | |
sw.Stop(); | |
Console.WriteLine(sw.Elapsed); | |
return sw.Elapsed; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment