当前位置:有风信息港IT学院编程技术.net → 用python测试代码的运行时间

用python测试代码的运行时间

减小字体 增大字体 作者:有风IT学院  来源:有风信息港  发布时间:2008-1-13 9:05:14
 原题:

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.


测试代码:

from time import clock as now

def getNatureSum(beg , max):
n = max / beg
end = beg * n
return (beg + end) * n / 2

def getSum(max) :
print getNatureSum( 3 , max ) + getNatureSum( 5 , max) - getNatureSum(15 , max)

start = now()
getSum(999)
finish = now()
print (finish-start)

改进后的代码:

from time import clock as now
start = now()
a = range(3 , 1000 , 3)
b = range(5 , 1000 , 5)
c = range(15 , 1000 , 15)

print sum(a) + sum(b) - sum(c)
finish = now()
print (finish-start)