Complexity of len() with regard to sets and lists

前端 未结 7 1305
耶瑟儿~
耶瑟儿~ 2021-02-04 23:38

The complexity of len() with regards to sets and lists is equally O(1). How come it takes more time to process sets?

~$ python -m timeit \"a=[1,2,3,         


        
7条回答
  •  [愿得一人]
    2021-02-05 00:17

    Many have noted that O(1) is not about performance on different data types, but about performance as a function of different input sizes.

    If you're trying to test O(1)-ness, you'd be looking for something more like

    ~$python -m timeit --setup "a=list(range(1000000))" "len(a)"
    10000000 loops, best of 3: 0.198 usec per loop
    
    ~$python -m timeit --setup "a=list(range(1))" "len(a)"
    10000000 loops, best of 3: 0.156 usec per loop
    

    Big data or little data, the time taken is quite similar. Per other posts, this separates setup time from testing time, but doesn't go as far as to reduce noise of len-time vs loop-time.

提交回复
热议问题