How to use timeit module

后端 未结 14 2824
猫巷女王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条回答
  •  萌比男神i
    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

提交回复
热议问题