Difference between revisions of "Python"
Jump to navigation
Jump to search
| Line 27: | Line 27: | ||
f.write("hello!\n") | f.write("hello!\n") | ||
# close automatic, even if exception | # close automatic, even if exception | ||
| + | </syntaxhighlight> | ||
| + | |||
| + | |||
| + | === Measure execution timing === | ||
| + | <syntaxhighlight lang="python"> | ||
| + | import time | ||
| + | start = time.perf_counter() | ||
| + | time.sleep(1) | ||
| + | end = time.perf_counter() | ||
| + | print(end - start) | ||
</syntaxhighlight> | </syntaxhighlight> | ||
Revision as of 21:07, 26 January 2023
Python Tips and Tricks
Array enumeration
For numpy
a = np.array([[1, 2], [3, 4]])
for index, x in np.ndenumerate(a):
print(index, x)
For usual python
a = np.array([[1, 2], [3, 4]])
for index, x in enumerate(a):
print(index, x)
Multiprocessing
Context
with open(filename, "w") as f:
f.write("hello!\n")
# close automatic, even if exception
Measure execution timing
import time
start = time.perf_counter()
time.sleep(1)
end = time.perf_counter()
print(end - start)