How to use timeit module

后端 未结 14 2632
猫巷女王i
猫巷女王i 2020-11-22 07:36

I understand the concept of what timeit does but I am not sure how to implement it in my code.

How can I compare two functions, say insertion_sort

相关标签:
14条回答
  • 2020-11-22 08:00

    lets setup the same dictionary in each of the following and test the execution time.

    The setup argument is basically setting up the dictionary

    Number is to run the code 1000000 times. Not the setup but the stmt

    When you run this you can see that index is way faster than get. You can run it multiple times to see.

    The code basically tries to get the value of c in the dictionary.

    import timeit
    
    print('Getting value of C by index:', timeit.timeit(stmt="mydict['c']", setup="mydict={'a':5, 'b':6, 'c':7}", number=1000000))
    print('Getting value of C by get:', timeit.timeit(stmt="mydict.get('c')", setup="mydict={'a':5, 'b':6, 'c':7}", number=1000000))
    

    Here are my results, yours will differ.

    by index: 0.20900007452246427

    by get: 0.54841166886888

    0 讨论(0)
  • 2020-11-22 08:00

    Example of how to use Python REPL interpreter with function that accepts parameters.

    >>> import timeit                                                                                         
    
    >>> def naive_func(x):                                                                                    
    ...     a = 0                                                                                             
    ...     for i in range(a):                                                                                
    ...         a += i                                                                                        
    ...     return a                                                                                          
    
    >>> def wrapper(func, *args, **kwargs):                                                                   
    ...     def wrapper():                                                                                    
    ...         return func(*args, **kwargs)                                                                  
    ...     return wrapper                                                                                    
    
    >>> wrapped = wrapper(naive_func, 1_000)                                                                  
    
    >>> timeit.timeit(wrapped, number=1_000_000)                                                              
    0.4458435332577161                                                                                        
    
    0 讨论(0)
  • 2020-11-22 08:03

    If you want to compare two blocks of code / functions quickly you could do:

    import timeit
    
    start_time = timeit.default_timer()
    func1()
    print(timeit.default_timer() - start_time)
    
    start_time = timeit.default_timer()
    func2()
    print(timeit.default_timer() - start_time)
    
    0 讨论(0)
  • 2020-11-22 08:06

    for me, this is the fastest way:

    import timeit
    def foo():
        print("here is my code to time...")
    
    
    timeit.timeit(stmt=foo, number=1234567)
    
    0 讨论(0)
  • 2020-11-22 08:09

    The built-in timeit module works best from the IPython command line.

    To time functions from within a module:

    from timeit import default_timer as timer
    import sys
    
    def timefunc(func, *args, **kwargs):
        """Time a function. 
    
        args:
            iterations=3
    
        Usage example:
            timeit(myfunc, 1, b=2)
        """
        try:
            iterations = kwargs.pop('iterations')
        except KeyError:
            iterations = 3
        elapsed = sys.maxsize
        for _ in range(iterations):
            start = timer()
            result = func(*args, **kwargs)
            elapsed = min(timer() - start, elapsed)
        print(('Best of {} {}(): {:.9f}'.format(iterations, func.__name__, elapsed)))
        return result
    
    0 讨论(0)
  • 2020-11-22 08:11

    simply pass your entire code as an argument of timeit:

    import timeit
    
    print(timeit.timeit(
    
    """   
    limit = 10000
    prime_list = [i for i in range(2, limit+1)]
    
    for prime in prime_list:
        for elem in range(prime*2, max(prime_list)+1, prime):
            if elem in prime_list:
                prime_list.remove(elem)
    """   
    , number=10))
    
    0 讨论(0)
提交回复
热议问题