python 中的时间排序

Time sorting in python

我搜索了这里的问题,发现有些问题与我的问题非常相似,但不完全是我想要的。如果之前确实有人提出过这个要求,我们深表歉意。

我希望能够在我的程序中对冒泡排序和插入排序选项进行计时,并将排序所花费的时间打印在已排序的随机整数数组下方。我已经尝试了几件事,但老实说,我什至不知道从哪里开始应对这部分挑战。如果您能给我任何帮助,我们将不胜感激

import random
import time

listnum = int(input("What size list would you like? "))
randomlist = random.sample(range(0, 5000), listnum)
print(randomlist)
sort_i = input("Would you like to sort your list Y or N? ")

if sort_i == "Y":
    search_i = input("Bubble sort or Insertion sort? ")
    if search_i == "Bubble sort":

        for i in range(len(randomlist) - 1, 0, -1):
            for j in range(i):
                if randomlist[j] > randomlist[j + 1]:
                    randomlist[j], randomlist[j + 1] = randomlist[j + 1], randomlist[j]


    if search_i == "Insertion sort":
        for i in range(1, len(randomlist)):
            key = randomlist[i]
            j = i - 1
            while j >= 0 and key < randomlist[j]:
                randomlist[j + 1] = randomlist[j]
                j -= 1
            randomlist[j + 1] = key
    print(randomlist)
elif sort_i == "N":

    lin_search_num = int(input("What number would you like to linear search? "))
    for s in range(len(randomlist)):
        if randomlist[s] == lin_search_num:
            print("Your number is at index " + str(s + 1))

我可以推荐这个吗?

import time

start = time.time() # in seconds since epoch
# your code
end = time.time()

print("{:.3f}".format(end - start), "seconds")

其实用time.process_time()代替time.time()会更好。

这行得通吗?我正在使用 time.time() 其中 returns 自纪元以来的秒数。

import random
import time

listnum = int(input("What size list would you like? "))
randomlist = random.sample(range(0, 5000), listnum)
print(randomlist)
sort_i = input("Would you like to sort your list Y or N? ")

if sort_i == "Y":
    search_i = input("Bubble sort or Insertion sort? ")
    st = time.time() # Start time in seconds
    if search_i == "Bubble sort":
        for i in range(len(randomlist) - 1, 0, -1):
            for j in range(i):
                if randomlist[j] > randomlist[j + 1]:
                    randomlist[j], randomlist[j + 1] = randomlist[j + 1], randomlist[j]

    if search_i == "Insertion sort":
        for i in range(1, len(randomlist)):
            key = randomlist[i]
            j = i - 1
            while j >= 0 and key < randomlist[j]:
                randomlist[j + 1] = randomlist[j]
                j -= 1
            randomlist[j + 1] = key
    et = time.time() # End time in seconds
    print(randomlist)
    print(f"Time taken to sort in seconds: {et - st}")
elif sort_i == "N":

    lin_search_num = int(input("What number would you like to linear search? "))
    st = time.time()
    for s in range(len(randomlist)):
        if randomlist[s] == lin_search_num:
            print("Your number is at index " + str(s + 1))
            print(f"Took {time.time() - st} seconds.")