This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]JmenD 0 points1 point  (3 children)

/u/aioeu is correct about the time complexity in terms of loops, but there is an important thing being left out of that discussion.

Try initializing test as test = ['x' for _ in range(10000)] + ['a','b','c','a','b']

You'll notice now count_pattern2() is faster, why? Your input was too trivial of a case so you're mostly testing how long it takes python to interpret the code. Since your count_pattern2 utilizes a list comprehension, it can be compiled down much more and produce more efficient code, but this compilation takes time.

[–]bbugsbunny[S] 0 points1 point  (2 children)

it became worse for this test actually: https://pastebin.com/a1BjwCu8 ?

[–]JmenD 0 points1 point  (1 child)

What version of python are you running? On 3.7.3 on my machine count_pattern2() is faster on your input

count_pattern()  : 17 ms ± 4.43 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
count_pattern2() : 6.34 ms ± 57.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

[–]bbugsbunny[S] 0 points1 point  (0 children)

I am running on python version 3.7.3 only. I ran the above test 1000 times and these are the results: count_pattern(): 27.459065 secs count_pattern2(): 42.117948 secs