Skip to main content
 首页 » 编程设计

python之如何提高这个程序的效率

2025年05月04日13insus

<分区>

下面的程序(在prime函数内)的运行时间是110.726383227秒

如果我运行相同的程序而不将它包装在一个函数(主要)中,它的运行时间是 222.006502634 秒

我通过将其包装在一个函数中,显着提高了性能。

还有没有可能提高这个程序的效率?

# This is a program to find sum of prime numbers till 2 billion 
 
def prime(): 
import time 
start_time = time.clock() 
 
num = 2 
j=1 
tot_sum = 0 
 
for num in xrange(2,2000000):  
    count = 0 
    for j in xrange(1,int(num**0.5)+1): # checking from 1 to sqrt(n)+1 
        if(num % j == 0): 
            count = count+1 
 
    if(count == 1): 
        tot_sum = tot_sum + num 
 
print "total sum is %d" % tot_sum 
 
print time.clock() - start_time, "seconds"