On Thu, 21 Jan 2016 06:30 pm, Paulo da Silva wrote: > Hi all. > > What is the fastest implementation of the following code?
Let's find out. Here are three different ways to do it: def g(p): return def f1(p=3): # argument with a default return g(p) def f2(): # no argument at all return g(3) from functools import partial f3 = partial(g, 3) # setup timing code from timeit import Timer t1 = Timer("f1()", "from __main__ import f1") t2 = Timer("f2()", "from __main__ import f2") t3 = Timer("f3()", "from __main__ import f3") Now let's see how long they take. This is using Python 2.7 on my computer. py> min(t1.repeat(repeat=7)) 0.43099188804626465 py> min(t1.repeat(repeat=7)) 0.4344518184661865 py> min(t1.repeat(repeat=7)) 0.42992687225341797 py> min(t2.repeat(repeat=7)) 0.43400001525878906 py> min(t2.repeat(repeat=7)) 0.432689905166626 py> min(t2.repeat(repeat=7)) 0.43417787551879883 py> min(t3.repeat(repeat=7)) 0.281879186630249 py> min(t3.repeat(repeat=7)) 0.27957892417907715 py> min(t3.repeat(repeat=7)) 0.28043699264526367 There's no visible difference between the first and second method. The third method, using functools.partial, is considerably faster, BUT remember that this only effects the time it takes to call the function g(). If g() actually does any work, the time spent doing the work will *far* outweigh the overhead of calling the function. -- Steven -- https://mail.python.org/mailman/listinfo/python-list