Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Done in no time?
#1
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!
Reply
#2
Try time.process_time_ns() perhaps.
Reply
#3
Numpy is generating an integer result. This is the result printed with the return type
Output:
n_dot_product = 833332333333500000 <class 'numpy.int64'>
Your looping calculation generates a float.
Output:
dot_product = 8.333323333340204e+17 <class '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.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020