Time function with arguments in python

Viewed 2378

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

3 Answers

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
Related