How to use timeit module

后端 未结 14 2631
猫巷女王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:11
    import timeit
    
    
    def oct(x):
       return x*x
    
    
    timeit.Timer("for x in range(100): oct(x)", "gc.enable()").timeit()
    
    0 讨论(0)
  • 2020-11-22 08:12
    # Генерация целых чисел
    
    def gen_prime(x):
        multiples = []
        results = []
        for i in range(2, x+1):
            if i not in multiples:
                results.append(i)
                for j in range(i*i, x+1, i):
                    multiples.append(j)
    
        return results
    
    
    import timeit
    
    # Засекаем время
    
    start_time = timeit.default_timer()
    gen_prime(3000)
    print(timeit.default_timer() - start_time)
    
    # start_time = timeit.default_timer()
    # gen_prime(1001)
    # print(timeit.default_timer() - start_time)
    
    0 讨论(0)
提交回复
热议问题