我们可以通过-mtimeit
.
$ python -mtimeit "B = [a * 2 for a in list(range(1000)) if a > 1]"
5000 loops, best of 5: 86.7 usec per loop
$ python -mtimeit "B = list(a * 2 for a in list(range(1000)) if a > 1)"
2000 loops, best of 5: 110 usec per loop
$ python -mtimeit "B = list(a * 2 for a in list(range(1000)) if a > 1)"
2000 loops, best of 5: 110 usec per loop
$ python -mtimeit "B = {str(a): a for a in list(range(1000)) if a > 1}"
1000 loops, best of 5: 273 usec per loop
$ python -mtimeit "B = set(str(a) for a in list(range(1000)) if a > 1)"
1000 loops, best of 5: 287 usec per loop
因此,如您所见,没有显着差异。
有了更大的列表,我们有:
$ python -mtimeit "B = [a * 2 for a in list(range(100000)) if a > 1]"
20 loops, best of 5: 11.1 msec per loop
$ python -mtimeit "B = list(a * 2 for a in list(range(100000)) if a > 1)"
20 loops, best of 5: 14.2 msec per loop
我们看到 3 毫秒的差异,更适合这种[]
情况。
有了更大的数字列表,我们有
$ python -mtimeit "B = [a * 2 for a in list(range(10000000)) if a > 1]"
1 loop, best of 5: 1.21 sec per loop
$ python -mtimeit "B = list(a * 2 for a in list(range(10000000)) if a > 1)"
1 loop, best of 5: 1.49 sec per loop
我们看到 0.28 秒的差异,再次[]
更快。