简体   繁体   中英

Don't understand how Timeit works. Need an explanation

I don't understand how I get timeit to work. I've made an example, where I want to calculate the difference in processing times. I would be eternally grateful if someone have the time to break it down for me.

Basse

def main():
    prod_nums = ['V475', 'F987', 'Q143', 'R688']

def search_fast(prod_nums):
    for item in prod_nums:
        if item == 'R688':
            return True
    return False

def search_slow(prod_nums):
    return_value = False
    for item in prod_nums:
        if item == 'R688': 
            return_value = True
    return return_value

If you want to pass arguments to your function you might want to use timeit.Timer , but make your list global like this:

prod_nums = ['V475', 'F987', 'Q143', 'R688']

And then run this:

from timeit import Timer
t = Timer(lambda: search_fast(prod_nums))
print t.timeit() # In my case will print 0.336354970932
t = Timer(lambda: search_slow(prod_nums))
print t.timeit() # 0.374251127243

timeit is useful when you want to inspect small piece of code in your dev environment.

If your function looks like that:

def search_slow():
    prod_nums = ['V475', 'F987', 'Q143', 'R688']
    return_value = False
    for item in prod_nums:
        if item == 'R688':
            return_value = True
    return return_value

You can use timeit.timeit

import timeit
timeit.timeit(search_slow)
>>> 0.3833189010620117

This will not return any result thou, only the time it took. This is another scenario in which you can use decorator. Basically you can use timeit to tell you how much time does it take for a function to execute, much like time sample_file.py in your terminal.

Based on python docs ( https://docs.python.org/2/library/timeit.html ): This module provides a simple way to time small bits of Python code. It has both a Command-Line Interface as well as a callable one. It avoids a number of common traps for measuring execution times. This module provides a simple way to time small bits of Python code. It has both a Command-Line Interface as well as a callable one. It avoids a number of common traps for measuring execution times.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM