Created
January 15, 2014 11:48
-
-
Save sokrato/8434869 to your computer and use it in GitHub Desktop.
Multiples of 3 and 5, http://projecteuler.net/problem=1, performance difference
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#-*- coding:utf8 -*- | |
from __future__ import print_function | |
import sys | |
import time | |
if sys.version_info < (3,0): | |
range = xrange | |
def f1(n=1000): | |
return sum(range(3, n, 3)) + sum(range(5, n, 5)) - sum(range(15, n, 15)) | |
def f2(n=1000): | |
return sum((i for i in range(3, n) if i%3==0 and i%5==0)) | |
def timeit(fn, args=None, n=1000): | |
t0 = time.time() | |
for i in range(0, n): | |
fn(args) | |
diff = time.time() - t0 | |
print("Done in %f s." % diff) | |
if __name__ == '__main__': | |
timeit(f1, 100000) | |
timeit(f2, 100000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
f1 is about as 10x fast as f2.