Skip to content

Instantly share code, notes, and snippets.

@ggarlic
Created May 28, 2016 20:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ggarlic/a6ba07a3c071a33915a6c638a29655a5 to your computer and use it in GitHub Desktop.
Save ggarlic/a6ba07a3c071a33915a6c638a29655a5 to your computer and use it in GitHub Desktop.
# coding: utf-8
import math
def map_loop():
list(map(math.sin, range(20000000)))
def for_loop():
r = []
for i in range(20000000):
r.append(math.sin(i))
def local_var_for_loop():
r = []
local_append = r.append
local_sin = math.sin
for i in range(20000000):
local_append(local_sin(i))
def bigger_step_for_loop():
r = []
local_append = r.append
local_sin = math.sin
for i in range(0, 20000000, 4):
local_append(local_sin(i))
local_append(local_sin(i+1))
local_append(local_sin(i+2))
local_append(local_sin(i+3))
import time
class Timer:
def __init__(self):
self.reset()
def reset(self):
self.start = 0.0
self.end = 0.0
self.interval = 0.0
def set(self):
self.start = time.time()
def stop(self, num):
self.end = time.time()
self.interval = (self.end - self.start)/num
print('costs time %f s' % self.interval)
number_tasks = 20000000
timer = Timer()
print('I: using for loop')
timer.set()
for i in range(10):
for_loop()
timer.stop(10)
print('I: using map()')
timer.set()
for i in range(10):
map_loop()
timer.stop(10)
print('I: using local_var_for_loop')
timer.set()
for i in range(10):
local_var_for_loop()
timer.stop(10)
print('I: using map outside function')
timer.set()
for i in range(10):
result = list(map(math.sin, range(20000000)))
timer.stop(10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment