计时做手术需要多长时间

2024-09-29 02:26:42 发布

您现在位置:Python中文网/ 问答频道 /正文

这里,del操作符是定时的:

from timeit import Timer

def build_list(n):
    return list(range(n))  # create list of 1 to n


def build_dict(n): # build dict = { 0:"0", 1:"1", 2:"2", ... n:"n" }
    return {i: str(i) for i in range(n)}  # from last listing in this chapter


def inx(x,n): # do in front, middle, end, and not found
    str(0) in x
    str(n//2) in x
    str(n-1) in x
    str("a") in x # not in it

timeList = Timer(
    "inx(x,n)",
    "from __main__ import n,build_list,inx; x = build_list(n)")

timeDict = Timer(
    "inx(x,n)",
    "from __main__ import n,build_dict,inx; x = build_dict(n)")

# get min of 5 runs of 5
print("N", "\t", "List", "\t", "Dict")
for size in range(1000, 100000+1, 5000):  # sizes to graph for n:
    n = size
    list_secs = timeList.repeat(5,5)
    dict_sect = timeDict.repeat(5,5)
    print(n, "\t", min(list_secs), "\t", min(dict_sect))

这一次,是计时执行in操作符而不是del操作符所需的时间。需要更改和添加哪些代码?你知道吗


Tags: ofinfromimportbuildfordefrange
1条回答
网友
1楼 · 发布于 2024-09-29 02:26:42

您需要为list和dict分别实现del,因为list采用整数作为索引,并且您的字典具有字符串键。因为我们不能删除列表或dict中不存在的元素,所以我省略了该部分。你知道吗

from timeit import Timer

def build_list(n):
    return list(range(n))  # create list of 1 to n


def build_dict(n): # build dict = { 0:"0", 1:"1", 2:"2", ... n:"n" }
    return {i: str(i) for i in range(n)}  # from last listing in this chapter


def delx(x, n):  # do in front, middle, end, and not found
    if x is list:
        del x[0]  # deleting first element in list
        del x[(n-1)//2]  # middle element delete n-1 because 0-th element is already deleted
        del x[-1]  # last element delete
    if x is dict:
        del x[str(0)]  # deleting first element in dict
        del x[str((n-1)//2)]  # deleting middle element from dict
        del x[str((n-2)-1)]  # last element delete n-2 because 0-th and middle element is already deleted
        # str("a") in x # not in it

timeList = Timer(
    "delx(x,n)",
    "from __main__ import n,build_list,delx; x = build_list(n)")

timeDict = Timer(
    "delx(x,n)",
    "from __main__ import n,build_dict,delx; x = build_dict(n)")

# get min of 5 runs of 5
print("N", "\t", "List", "\t", "Dict")
for size in range(1000, 100000+1, 5000):  # sizes to graph for n:
    n = size
    list_secs = timeList.repeat(5,5)
    dict_sect = timeDict.repeat(5,5)
    print(n, "\t", min(list_secs), "\t", min(dict_sect))

相关问题 更多 >