简体   繁体   English

与Java或C#中的相同算法相比,为什么在Python中这种主要筛子这么慢?

[英]Why is this prime sieve so slow in Python compared with the same algorithm in Java or C#?

I'm trying to build a sieve for project Euler solutions. 我正在尝试为Euler项目解决方案建立一个筛子。 I need primes up until about 100M, preferably with option to go much higher. 我需要预充至大约100M,最好选择更高。

This implementation I have works fine, but is very slow: 我执行的此实现工作正常,但速度很慢:

class Primes:
__size = None
__sieve = []
__primes = []

def __init__(self, size):
    self.__size = size
    self.__sieve = [True] * size
    for x in range(2, size):
        if self.__sieve[x]:
            self.foundPrime(x);

def foundPrime(self, x):
    self.__primes.append(x)
    for duplicate in range(2 * x, self.__size, x):
        self.__sieve[duplicate] = False

For a sieve sized 100M, this initialization takes about 70 seconds on my fairly high-end computer. 对于大小为100M的筛子,此初始化在我相当高端的计算机上大约需要70秒。 Does anyone know why? 有人知道为什么吗? Because in Java and C# this took me about 1 second... 因为在Java和C#中,这花了我大约1秒钟的时间...

So, this post is different from other posts in that I do not want to know how to implement the algorithm, I want to understand why it is so slow in Python. 因此,本篇文章与其他文章的不同之处在于,我不想知道如何实现该算法,而是想了解为什么它在Python中如此之慢。

Some prints give me the information that about 50% of the time is spent on finding the first 100K primes. 一些印刷品给我的信息是大约50%的时间都花在寻找最初的100K素数上。

In various benchmarks, for what they are worth, Python is anywhere from the same speed to 50 times slower than Java, dependent on the problem. 在各种基准测试中,就其价值而言,取决于问题,Python的速度是Java的两倍,甚至比Java慢50倍。 This is largely due to Python being interpreted, and Java being compiled (even if not to native). 这在很大程度上是由于Python被解释,而Java被编译(即使不是本机)。 Ruby posts similar scores as Python. Ruby发布的分数与Python类似。

Language design also gives Java and C# some advantages. 语言设计还为Java和C#提供了一些优势。

There are two good ways to speed things up, aside of more efficient Python methods: use pypy, which essentially bytecompiles your python, similar to Java, or write the critical sections in a faster language such as C, and call those routines from Python, a task which is actually pretty easy, assuming you are good with the fast language. 除了更有效的Python方法外,还有两种加快速度的好方法:使用pypy,它实际上类似于Java来对python进行字节编译,或者以更快的语言(例如C)编写关键部分,然后从Python调用这些例程,假设您精通快速语言,这实际上是一件容易的事。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM