我该如何使用来比较我自己的函数(例如“ ”和“ ”)timeit的性能?insertion_sorttim_sort
要使用该模块比较您自己的函数(例如insertion_sort和)的性能,您需要遵循以下步骤:tim_sort``timeit
insertion_sort
tim_sort``timeit
tim_sort
timeit.timeit()
以下是一个例子:
Python复制代码import timeit # Define your sorting functions def insertion_sort(arr): for i in range(1, len(arr)): key = arr[i] j = i - 1 while j >= 0 and key < arr[j]: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key return arr def tim_sort(arr): return sorted(arr) # Using Python's built-in Timsort # Create the setup code setup_code = """ from __main__ import insertion_sort, tim_sort import random arr = [random.randint(0, 1000) for _ in range(1000)] """ # Create the test code for insertion_sort insertion_sort_code = """ arr_copy = arr[:] insertion_sort(arr_copy) """ # Create the test code for tim_sort tim_sort_code = """ arr_copy = arr[:] tim_sort(arr_copy) """ # Use timeit to measure the performance insertion_sort_time = timeit.timeit(stmt=insertion_sort_code, setup=setup_code, number=100) tim_sort_time = timeit.timeit(stmt=tim_sort_code, setup=setup_code, number=100) print(f"Insertion Sort Time: {insertion_sort_time}") print(f"Tim Sort Time: {tim_sort_time}")
from __main__ import insertion_sort, tim_sort
import random
random
arr = [random.randint(0, 1000) for _ in range(1000)]
arr_copy = arr[:]
insertion_sort(arr_copy)
tim_sort(arr_copy)
number=100
insertion_sort通过运行此脚本,您可以比较和函数的性能。根据您的性能要求,根据需要tim_sort调整列表的大小和迭代次数(参数)。number
通过运行此脚本,您可以比较和函数的性能。根据您的性能要求,根据需要
调整列表的大小和迭代次数(参数)。