Skip to content

Instantly share code, notes, and snippets.

@ayende

ayende/Bench.cs Secret

Created August 8, 2023 09:03
Show Gist options
  • Save ayende/563e0e4b0dae1bf986a660076f143aa6 to your computer and use it in GitHub Desktop.
Save ayende/563e0e4b0dae1bf986a660076f143aa6 to your computer and use it in GitHub Desktop.
using System.Diagnostics;
var nums = Enumerable.Range(0, 100_000).Select(_ => Random.Shared.Next()).ToArray();
for (int i = 0; i < 3; i++)
{
{
var total = Stopwatch.StartNew();
var countPrimes = 0;
Stopwatch countTime = new();
foreach (var num in nums)
{
countTime.Start();
if (IsPrime(num))
countPrimes++;
countTime.Stop();
}
Console.WriteLine(countPrimes + " in " + total.ElapsedMilliseconds + " without " + countTime.ElapsedMilliseconds);
}
{
var total = Stopwatch.StartNew();
var countPrimes = 0;
foreach (var num in nums)
{
if (IsPrime(num))
countPrimes++;
}
Console.WriteLine(countPrimes + " in " + total.ElapsedMilliseconds);
}
}
bool IsPrime(int n)
{
if (n == 1)
{
return false;
}
int i = 2;
while (i * i <= n)
{
if (n % i == 0)
{
return false;
}
i += 1;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment