欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python in列表list和in集合set耗时对比

程序员文章站 2022-05-14 09:05:27
...
# -*- coding: utf-8 -*-
import random
import time


def count_time(fun):
    def warpper(*args):
        s_time = time.time()
        fun(*args)
        e_time = time.time()
        t_time = e_time - s_time
        print('%s耗时:%s' % (fun.__name__, t_time))

    return warpper



@count_time
def in_list(times,size):
    larget_list = list(range(size))
    count = 0
    for i in range(times):
        num = random.randint(0, size * 2)
        if num in larget_list:
            count += 1
    print count


@count_time
def in_set(times,size):
    larget_set = set(range(size))
    count = 0
    for i in range(times):
        num = random.randint(0, size * 2)
        if num in larget_set:
            count += 1
    print count


if __name__ == '__main__':
    times = 10000
    size = 10000
    in_set(times,size)
    in_list(times,size)

 

相关标签: python