3 ms·
You are correct. To µbench this, you'd want to use `-s` to set up the base object which both snippets then convert. > python -m timeit -s "t = (1, 2, 'a')
by masklinn 3y ago
You are correct.
To µbench this, you'd want to use `-s` to set up the base object which both snippets then convert.
> python -m timeit -s "t = (1, 2, 'a')" "list(t)"
10000000 loops, best of 5: 39.8 nsec per loop
> python -m timeit -s "t = (1, 2, 'a')" "[*t]"
10000000 loops, best of 5: 25.1 nsec per loop
> python -m timeit -s "[1, 2, 'a']"
50000000 loops, best of 5: 4.28 nsec per loop
(this is 3.11.2 on an M1 Pro)
- charlieyu1 3y agoThe third method should be clearly the fastest one, the other two we are building a tuple then convert to a list
- masklinn 3y ago`-s` stands for "setup", the building of the tuple is only done once, and it is not part of the benchmark. All three versions only bench the construction of the list, two of them from a tuple, while the third is a list literal. However if you plug it into `dis` you'll see that it compiles to loading a const tuple and creating a list from that >>> dis.dis("[1, 2, 'a']") 0 0 RESUME 0 1 2 BUILD_LIST 0 4 LOAD_CONST 0 ((1, 2, 'a')) 6 LIST_EXTEND 1 8 RETURN_VALUE >>> dis.dis("[*t]") 0 0 RESUME 0 1 2 BUILD_LIST 0 4 LOAD_NAME 0 (t) 6 LIST_EXTEND 1 8 RETURN_VALUE
- tczMUFlmoNk 3y agoShouldn't you omit `-s` in the last one? I think you're just effectively testing an empty loop, since you're only actually creating the list in the setup phase. On my machine, the tests that actually do work are: $ python3 -m timeit -s 't = (1, 2, "a")' 'list(t)' 5000000 loops, best of 5: 44.8 nsec per loop $ python3 -m timeit -s 't = (1, 2, "a")' '[*t]' 10000000 loops, best of 5: 22.9 nsec per loop $ python3 -m timeit '[1, 2, "a"]' 10000000 loops, best of 5: 23.1 nsec per loop ...compared to the empty ones: $ python3 -m timeit -s '[1, 2, "a"]' 50000000 loops, best of 5: 5.43 nsec per loop $ python3 -m timeit '' 50000000 loops, best of 5: 5.8 nsec per loop (11th gen Intel i7 laptop, Python 3.10.6)
- masklinn 3y agoYou’re completely right, I missed stripping it, my bad (and from the disassembly below we can see that the second and third do about the same operation so they should have very similar if not identical performances, I should have caught that).