comparison of four ways to generating a list

from time import time

def timeit(func):
    '''Use this decorator to measure execution time of a function.
       eg.
       @timeit
       def yourFunction(args):
            dosomething...
    '''
    def wrapper(*args, **kwargs):
        start = time()
        res = func(*args, **kwargs)
        elapsed = time() - start
        print('Function %s costs time: %10.6f seconds.' % (func.__name__, elapsed))
        return res
    return wrapper

# 4 different ways to generating a list of n numbers starting with 0

# Using concatenation
@timeit
def gen_list_1(n):
    L = []
    for i in range(n):
        L = L + [i]

# Using append method
@timeit
def gen_list_2(n):
    L = []
    for i in range(n):
        L.append(i)

# Using list comprehension
@timeit
def gen_list_3(n):
    L = [i for i in range(n)]

# Using list construction
@timeit
def gen_list_4(n):
    L = list(range(n))

if __name__ == '__main__':
    gen_list_1(100000)
    gen_list_2(100000)
    gen_list_3(100000)
    gen_list_4(100000)
   

The result as below:

Function gen_list_1 costs time: 19.48219490 seconds.
Function gen_list_2 costs time: 0.01999998 seconds.
Function gen_list_3 costs time: 0.00999999 seconds.
Function gen_list_4 costs time: 0.00999999 seconds.



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值