正如其他人所提到的,主要问题似乎是在 Python 2.7 中使用 range 而不是 range。使用%timeit,如果要使用xrange(Python 2.7),这两个函数几乎相同。
%timeit isPrimeRange(n)
100000 loops, best of 3: 15.2 µs per loop
%timeit isPrimeWhile(n)
100000 loops, best of 3: 15.8 µs per loop
%load_ext line_profiler
%load_ext memory_profiler
from isPrimeRange import isPrimeRange
from isPrimeWhile import isPrimeWhile
n = 353591872901
isPrimeRange:线分析器
%lprun -f isPrimeRange isPrimeRange(n)
Timer unit: 1e-06 s
**Total time: 5.5e-05 s**
File: isPrimeRange.py
Function: isPrimeRange at line 1
Line # Hits Time Per Hit % Time Line Contents
==============================================================
1 def isPrimeRange(n):
2 82 25 0.3 45.5 for i in xrange(2,n/2+1):
3 82 29 0.4 52.7 if(n%i == 0):
4 1 1 1.0 1.8 return i
5 return n
isPrimeWhile:线分析器
%lprun -f isPrimeWhile isPrimeWhile(n)
Timer unit: 1e-06 s
**Total time: 9e-05 s**
File: isPrimeWhile.py
Function: isPrimeWhile at line 3
Line # Hits Time Per Hit % Time Line Contents
==============================================================
3 def isPrimeWhile(n):
4 1 1 1.0 1.1 i = 2
5 82 34 0.4 37.8 while(i <= n/2+1):
6 82 31 0.4 34.4 if(n%i == 0):
7 1 0 0.0 0.0 return i
8 81 24 0.3 26.7 i += 1
9 return n
使用 iPython 的内存分析器,您可以看到两者使用相同数量的内存。
isPrimeRange:内存分析器
%mprun -f isPrimeRange isPrimeRange(n)
('',)
Filename: isPrimeRange.py
Line # Mem usage Increment Line Contents
================================================
1 24.2 MiB 0.0 MiB def isPrimeRange(n):
2 24.2 MiB 0.0 MiB for i in xrange(2,n/2+1):
3 24.2 MiB 0.0 MiB if(n%i == 0):
4 24.2 MiB 0.0 MiB return i
5 return n
isPrimeWhile:内存分析器
%mprun -f isPrimeWhile isPrimeWhile(n)
('',)
Filename: isPrimeWhile.py
Line # Mem usage Increment Line Contents
================================================
3 24.2 MiB 0.0 MiB def isPrimeWhile(n):
4 24.2 MiB 0.0 MiB i = 2
5 24.2 MiB 0.0 MiB while(i <= n/2+1):
6 24.2 MiB 0.0 MiB if(n%i == 0):
7 24.2 MiB 0.0 MiB return i
8 24.2 MiB 0.0 MiB i += 1
9 return n