简体   繁体   English

Python代码比同一C ++代码更慢?

[英]Python Code is Way Slower Than The Same C++ Code?

The following is my answer to Project Euler's third problem . 以下是我对欧拉计划的第三个问题的回答。 Here's the python implementation: 这是python的实现:

def isPrime(n):
    for i in range(n/2)[3::2]:
        if n % i == 0:
            return False
    return True

def largestPrime(n):
    for i in range(3, n/2):
        if n % i == 0 and isPrime(n/i):
            return n/i
    return -1

largestPrime(600851475143)

And here's the same implementation rewritten in C++: 这是用C ++重写的相同实现:

#include <iostream>
using namespace std;

bool isPrime(long n)
{
    for(int i = 3; i < n/2; i+=2)
    {
        if(n % i == 0)
            return false;
    }
    return true;
}

long largestPrime(long n)
{
    for(int i = 2; i < n/2; i++)
    {
        if(n % i == 0 and isPrime(n/i))
            return n/i;
    }
    return -1;
}

int main()
{
    cout << largestPrime(600851475143) << endl;
    return 0;
}

When I run the C++ code, it computes the correct answer (6857) within seconds. 当我运行C ++代码时,它将在几秒钟内计算出正确的答案(6857)。 But when I run the python code, it seems to go on forever. 但是,当我运行python代码时,它似乎永远存在。 What's is it that python performance is so poor here? python性能太差了是什么意思?

Its because Python is an interpreted language while C++ is a compiled language. 这是因为Python是一种解释语言,而C ++是一种编译语言。

See this stack overflow question for a more in-depth description of the differences between the two. 请参阅此堆栈溢出问题,以更深入地描述两者之间的区别。 Note that this touches the surface of it. 请注意,这触及了它的表面。

Compiled vs. Interpreted Languages 编译语言与口译语言

Also refer to this page on the Python site for brief descriptions of Python compared to other programming languages. 另请参阅Python站点上的此页面,以获取与其他编程语言相比Python的简要说明。

https://www.python.org/doc/essays/comparisons/ https://www.python.org/doc/essays/comparisons/

A) Python is interpreted, C is compiled. A)Python被解释,C被编译。 The latter class is almost always faster than the former. 后一类几乎总是比前一类快。

B) isPrime is executed a number of times. B) isPrime被执行了很多次。 In it, you have range(n/2)[3::2] , which will construct (a rather large) array many times. 其中有range(n/2)[3::2] ,它将多次构造(相当大的)数组。 In contrast, your C code only has a simple loop, without memory allocation and initialisation. 相反,您的C代码只有一个简单的循环,没有内存分配和初始化。

C) Tony D's question comment might well have merit. C)托尼D的问题评论可能很有价值。 Check your long size. 检查您的long尺码。

Python is, as previously mentioned, a interpreted language, but another drawback is you are more than likely running it through an IDE such as IDLE or IDLE3. 如前所述,Python是一种解释型语言,但是另一个缺点是您很有可能通过IDLE或IDLE3等IDE运行它。 These are made With Python and can take up more cpu usage than a compiled language, such as C++. 它们是使用Python制作的 ,比诸如C ++之类的编译语言占用的CPU使用率更高。 I hope this helped in any way in your favor. 希望这对您有所帮助。 ~Th3T3ch13 〜Th3T3ch13

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

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