|
|
|
|
|
by MooMooMilkParty
3406 days ago
|
|
I wrote up a small script to test this out for python (at bottom of this post). The results on my laptop are about 8.0 seconds for unsorted and 7.6 seconds for the sorted version. I'm assuming that the discrepancy for python is much smaller due to the slow nature and high overhead of the language (or at least the way I've used it here), but I would be interested to know: how would one go about finding out what the python interpreter is doing beneath the surface? Edit: After running with a wider range of parameters, it seems that the difference is always roughly the same order of magnitude. To investigate further, I included the sort into the second timing to double check and for 3276800 elements it's still a bit faster overall when you sort the array. #!/usr/bin/env python
import time
import numpy as np
def main(n=32768):
arr = np.random.randint(0, 256, n)
t0 = time.time()
sum1 = do_loop(arr)
t1 = time.time()
arr = np.sort(arr)
t2 = time.time()
sum2 = do_loop(arr)
t3 = time.time()
assert sum1 == sum2
print(" Unsorted execution time: {} seconds".format(t1-t0))
print(" Sorted execution time: {} seconds".format(t3-t2))
def run_many(func):
def wrapper(arg):
for t in range(1000):
func(arg)
return func(arg)
return wrapper
@run_many
def do_loop(arr):
tot = 0
for i in arr:
if i >= 128:
tot += i
return tot
if __name__ == '__main__':
main()
|
|