forked from kiat/Elements-of-Software-Design
-
Notifications
You must be signed in to change notification settings - Fork 0
/
performance.py
53 lines (29 loc) · 954 Bytes
/
performance.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# Move Data operations into Numpy
# Use builtin functions and libraries
newlist = []
for word in oldlist:
newlist.append(word.upper())
newlist = map(str.upper, oldlist) # wiki cites map as a for loop moved into C code
# Reduce Memory Footprints
# # slow
# inefficient because a new string gets created
msg = 'hello ' + my_var + ' world'
# faster
msg = 'hello %s world' % my_var
# or better:
msg = 'hello {} world'.format(my_var)
# Do only necessary things inside a loop
myfunc = myObj.func
fcor i in range(n):
myfunc(i) # faster than myObj.func(i)
# List Comprehensive
# It is more about python style. It is not so much improving the performance.
newlist = []
for word in wordlist:
newlist.append(word.upper())
A better way to write this code is:
newlist = list(map(str.upper, wordlist))
# Check your profile
# You can use a profiler, for example:
# python -m cProfile [-o output_file] [-s sort_order] myscript.py
#