With the C# application, it takes 4.99s.
If python, it takes about 80s. Python + numba may be close to C#.
C# codes are as below:
//Sieve of Eratosthenes 埃氏筛法
static void Main(string[] args)
{
DateTime t1 = DateTime.Now;
List<Int64> lstPN = FindPrimeNumber(Convert.ToInt32(Math.Pow(10,8)));
DateTime t2 = DateTime.Now;
TimeSpan secondSpan = new TimeSpan(t2.Ticks - t1.Ticks);
Console.WriteLine($"从2到10的8次方范围内素数共{lstPN.Count}个");
Console.WriteLine($"共耗时{secondSpan.TotalSeconds}秒");
Console.ReadLine();
}
static List<Int64> FindPrimeNumber(int n)
{
List<Int64> lstPN = new List<Int64>();
bool[] a = Enumerable.Repeat(true, n+1).ToArray();
for (Int64 i = 2; i < n; i++)
{
if (a[i])
{
lstPN.Add(i);
for (Int64 j = i * i; j <= n; j += i)
a[j] = false;
}
}
return lstPN;
}
这篇博客对比了C#和Python实现埃氏筛法找素数的效率。C#程序在找出10的8次方范围内素数只需4.99秒,而Python原生实现则需要约80秒。通过使用numba库优化,Python性能显著提升,接近C#。文章提供了C#代码示例,并探讨了Python+numba的优化效果。
https://zhuanlan.zhihu.com/p/400818808
1万+

被折叠的 条评论
为什么被折叠?



