On 21/11/2016 02:48, Steve D'Aprano wrote:
On Mon, 21 Nov 2016 07:46 am, DFS wrote:

start=time.clock()
for i in range(loops):
     np.cross(x,y)
print "Numpy, %s loops: %.2g seconds" %(loops,time.clock()-start)

However, your code is not a great way of timing code. Timing code is *very*
difficult, and can be effected by many things, such as external processes,
CPU caches, even the function you use for getting the time. Much of the
time you are timing here will be in creating the range(loops) list,
especially if loops is big.

But both loops are the same size. And that overhead can quickly be disposed of by measuring empty loops in both cases. (On my machine, about 0.006/7 seconds for loops of 100,000.)

The best way to time small snippets of code is to use the timeit module.
Open a terminal or shell (*not* the Python interactive interpreter, the
operating system's shell: you should expect a $ or % prompt) and run timeit
from that. Copy and paste the following two commands into your shell
prompt:


python2.7 -m timeit --repeat 5 -s "import numpy as np" \
-s "x = np.array([1, 2, 3])" -s "y = np.array([4, 5, 6])" \
-- "np.cross(x, y)"


python2.7 -m timeit --repeat 5 -s "x = [1, 2, 3]" \
-s "y = [4, 5, 6]" -s "z = [0, 0, 0]" \
-- "z[0] = x[1]*y[2] - x[2]*y[1]; z[1] = x[2]*y[0] - \
x[0]*y[2]; z[2] = x[0]*y[1] - x[1]*y[0]"

Yes, I can see that typing all the code out again, and remembering all those options and putting -s, -- and \ in all the right places, is a much better way of doing it! Not error prone at all.

--
bartc
--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to