0

I am attempting to use timeit to keep track of how long a sorting algorithm takes to finish. However, it seems I can't even find an answer online how to exactly run timeit with functions that were originally written in another module. I've tried various setups and string inputs but am finding myself lost on this.

I tried using "t = timeit.Timer('sort.bubble(temp_array)')," but printing out the timer objects only gives me the memory addresses and cannot be converted to an integer...

In this case, I am calling bubble sort from another module.

#This section is on a timetests.py file
import random
import sort
import timeit

test_array1 = [random.randint(0, 500) for i in range(10)]
arrays_to_sort = [test_array1]
bubble_times = []

for a in range(len(arrays_to_sort)):
    temp_array = arrays_to_sort[a]
    t = timeit(sort.bubble(temp_array))
    bubble_times.append(t)
**t = timeit(sort.bubble(temp_array))** #code is definitely not correct here

#This file is on sort.py
def bubble(list):
    for current_pass in range(len(list) - 1, 0, -1):
        for element in range(current_pass):
        #Swap the element if the current one is smaller than
        #next one
            if list[element] > list[element + 1]:
                temp = list[element]
                list[element] = list[element + 1]
                list[element + 1] = temp
    return list
小苹果
  • 11
  • 3
  • Have you read the [manual](https://docs.python.org/3/library/timeit.html)? – Nick May 20 '22 at 06:57
  • Yes, and I am extremely confused. I tried to do t = timeit.timeit("sort.bubble(temp_array)", setup = "from sort import bubble"), but sort is not defined in this case. Maybe I need to use the setup and other items? – 小苹果 May 20 '22 at 07:06

1 Answers1

0

You need to function bubble and variable temp_array in the local environment.

Try:

t = timeit.timeit("bubble(temp_array)", setup = "from sort import bubble; from __main__ import temp_array"),
bubble_times.append(t)

Explanation:

  1. So we use bubble() since that's the way to access an imported function
    • you would use sort.bubble() if you had imported the sort module rather than just a function from the module
  2. We have to also bring in temp_array (assuming we are running timetests.py as the main module)

Using lambda function

Another option is use lambda to create a zero argument function which we pass to timeit. Note: checkout how to pass parameters of a function when using timeit.Timer()

t = timeit.timeit(lambda: sort.bubble(temp_array))
DarrylG
  • 16,732
  • 2
  • 17
  • 23