Created
November 19, 2016 18:57
-
-
Save coldfix/7e0bfb82b4ff80761e37937eb86752e0 to your computer and use it in GitHub Desktop.
Timing methods to clip negative numbers. http://stackoverflow.com/questions/3391843/how-to-transform-negative-elements-to-zero-without-a-loop
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
import numpy as np | |
from timeit import timeit | |
def timing(neg_ratio=0.5): | |
a0 = np.random.uniform(0, 1, 20000000) - neg_ratio | |
globals = { | |
'a0': a0, | |
'np': np, | |
} | |
def fair(stmt): | |
init = 'a = a0.copy(); ' | |
time = timeit(init+stmt, globals=globals, number=10) | |
print("{:30} {:.3f}s".format(stmt, time)) | |
print("Timing for {:.2f}".format(ratio)) | |
fair('b = np.where(a>0, a, 0)') | |
fair('b = a.clip(min=0)') | |
fair('a[a<0] = 0') | |
fair('a[np.where(a<0)] = 0') | |
fair('b = a * (a>0)') | |
fair('a *= a>0') | |
print("") | |
if __name__ == '__main__': | |
for ratio in np.linspace(0.0, 1.0, 11): | |
timing(ratio) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment