How to use timeit module

后端 未结 14 2655
猫巷女王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 07:54

    You would create two functions and then run something similar to this. Notice, you want to choose the same number of execution/run to compare apple to apple.
    This was tested under Python 3.7.

    Here is the code for ease of copying it

    !/usr/local/bin/python3
    import timeit
    
    def fibonacci(n):
        """
        Returns the n-th Fibonacci number.
        """
        if(n == 0):
            result = 0
        elif(n == 1):
            result = 1
        else:
            result = fibonacci(n-1) + fibonacci(n-2)
        return result
    
    if __name__ == '__main__':
        import timeit
        t1 = timeit.Timer("fibonacci(13)", "from __main__ import fibonacci")
        print("fibonacci ran:",t1.timeit(number=1000), "milliseconds")
    

提交回复
热议问题