import string import random import timeit from timeit import Timer def random_string(length=16): rule = string.ascii_letters + string.digits char_list = random.sample(rule, length) return ''.join(char_list) def random2(): char = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' res = '' for i in range(16): res += random.choice(char) return res t1=Timer("random_string()","from __main__ import random_string").timeit(100000) t2=Timer("random2()","from __main__ import random2").timeit(100000) print(t1) print(t2)