Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time function with arguments in python

I have a function with a string as an argument that returns two lists

e.g.

def return_words(string):
    return list1, list2

Obviously there's code in between. I want to be able to time this function accurately for various strings as I need to improve efficiency when long strings are inputted.

Sorry if this is a trivial question as I am new to python.

Thanks

like image 358
user2201609 Avatar asked Mar 25 '26 22:03

user2201609


2 Answers

You can use timeit module and pass the arguments in timeit's setup argument:

from timeit import timeit


inp = """
def return_words(string):
    return list1, list2
return_words(string)
   """

for s in list_of_inputs:
    print '{}'.format(s), '->', timeit(stmt=inp,
                                       number=1000000,
                                       setup="string = '{}'".format(s))

Demo :

inp = """
def return_words(string):
    return [i for i in string if i.isdigit()]

return_words(string)
   """

list_of_inputs = ['inputstring1', 'inp2']

for s in list_of_inputs:
    print '{}'.format(s), '->', timeit(stmt=inp,
                                       number=1000000,
                                       setup="string = '{}'".format(s))

Output:

inputstring1 -> 0.986068964005
inp2 -> 0.548749923706

Note that timeit also accepts a function as the first argument which is defined in your code, but you can not pass argument to it. In that case it's better to create a wrapper which will call your function with relative arguments. Read http://pythoncentral.io/time-a-python-function/ for more info.

like image 109
Mazdak Avatar answered Mar 27 '26 10:03

Mazdak


With Python 3.7, there is a new nanosecond timer:

>>> st={time.time_ns() for e in range(10000000)}
>>> (max(st)-min(st))/10**9
2.275888

So a range counter (and calling time.time_ns() that many times) to 10,000,000 takes 2.275888 seconds...

There is also a nanosecond precision performance timer (how long does the range part take?):

>>> t1=time.perf_counter_ns(); x={y for y in range(10000000)}; t2=time.perf_counter_ns()
>>> (t2-t1)/10**9
0.860256448

Or the timeit module:

>>> timeit.timeit("x={_ for _ in range(10000000)}",number=1)
0.7478707919999579
like image 20
dawg Avatar answered Mar 27 '26 12:03

dawg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!