为什么这些Python代码的表现如此不同

whi*_*kid 11 python performance time python-2.7 josephus

请看下面的代码来解决同一组问题,我不认为提到问题无论如何会帮助目的,这是Josephus问题的又一次迭代:

解决方案1:

import sys
from math import log

cases= int(sys.stdin.readline())
current= 0
while current < cases:
    current += 1
    n = int(sys.stdin.readline())
    print 2*(n - 2**(int(log(n,2))))+1
Run Code Online (Sandbox Code Playgroud)

该解决方案在累计1.0912秒内解决了给定的10个测试用例,并消耗了4360KiB的内存.

解决方案2:

def josephus_2( n ):
    from math import log
    return 2*(n - 2**(int(log(n,2))))+1

import sys
cases= int(sys.stdin.readline())
current= 0
while current < cases:
    current += 1
    n = int(sys.stdin.readline())
    print josephus_2( n )
Run Code Online (Sandbox Code Playgroud)

该解决方案在总共1.0497秒和640KiB内存中解决了相同的10个测试用例.

作为一个Python n00b,我想知道,虽然根据在线评判,我获得两个相同的积分,但是什么使解决方案2比1更快,更高的内存效率?我知道时间差可以听起来很少,但同时我在最快的解决方案上排名第一,甚至比c/c ++/perl提交更快

这个截图有帮助吗?

Dev*_*per 1

在我以前的经验中,我记得我发现有时将计算部分放入函数(方法)中可能会提高性能:
我刚刚使用以下简单代码重新体验了:

n = 1000000
def compute(n):
    j = 0
    for i in xrange(n):
        j += 1

tic()
compute(n)
toc()

>>> 0.271 s

tic()
j = 0
for i in xrange(n):
    j += 1
toc()

>>> 0.849 s
Run Code Online (Sandbox Code Playgroud)

结果显示第一个(使用计算)为 0.271 秒,而内联代码为 0.849 秒。这是显着的改进,无需更改主计算部分中的任何内容!所以重点是使用一种可以提高性能的方法。

以下是您可用于性能比较的代码:

from __future__ import division
from time import clock

def compute(n):
    j = 0
    for i in xrange(n):
        j += 1

n = 1000000
print 'solution (2) using a method call...'
t0 = clock()
compute(n)
print clock()-t0
#>>> ~0.2415...                              #faster (solution 2)

print 'solution (1) all inline code...'
t0 = clock()
j = 0
for i in xrange(n):
    j += 1
print clock()-t0
#>>> ~0.6169...                              #slower (solution 1)
Run Code Online (Sandbox Code Playgroud)