Done in no time? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Done in no time? (/thread-34678.html) |
Done in no time? - Mark17 - Aug-20-2021 Hi all, Here's some (slightly modified) code I got from an article on vectorization: # Dot product import time import numpy import array # 8 bytes size int for k in range(11): a = array.array('q') for i in range(1000000): a.append(i); b = array.array('q') for i in range(1000000, 2000000): b.append(i) # classic dot product of vectors implementation tic = time.process_time() dot = 0.0; for i in range(len(a)): dot += a[i] * b[i] toc = time.process_time() print("dot_product = "+ str(dot)); print("Computation time = " + str(1000*(toc - tic )) + "ms") n_tic = time.process_time() n_dot_product = numpy.dot(a, b) n_toc = time.process_time() print("\nn_dot_product = "+str(n_dot_product)) print("Computation time = "+str(1000000000*(n_toc - n_tic ))+"nanosec") #increased to nano in case of rounding off. 0 ET??? print('n_toc = ',n_toc) print('n_tic = ',n_tic) print() print()Partial output looks like this: dot_product = 8.333323333340204e+17 Computation time = 265.625ms n_dot_product = 833332333333500000 Computation time = 0.0nanosec n_toc = 17.765625 n_tic = 17.765625 I have two questions. First, why are dot_product and n_dot_product displayed in different formats (the former being scientific notation)? Second, why does the latter say ZERO time? I've re-run this many times and that shows up as zero every single time. I even increased the number of iterations 10x and multiplied by an additional 1,000,000 to see if it had been rounded off and that doesn't appear to be the case. Thanks! RE: Done in no time? - Gribouillis - Aug-20-2021 Try time.process_time_ns() perhaps.
RE: Done in no time? - deanhystad - Aug-20-2021 Numpy is generating an integer result. This is the result printed with the return type Your looping calculation generates a float. dot_product is a float because you initialize dot as a float (dot = 0.0)Your time is zero because numpy is calculating the dot product using highly optimized code. The amount of time is shorter than the clock resolution. Multiplying the reported time does not provide more resolution (if a - a is zero, so is 1000*a-1000*a). I put the calculation in a loop and ran it 1000 times and it took 0.84375 seconds, but much of that was likely the loop. |