ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 파이썬 효율적인 리스트 사용법
    Python/이것저것 파이썬 2022. 7. 24. 05:57
    반응형

    리스트 컴프리헨션이 가장 빠르다. 

    import time
    
    
    def time_log(original_fn):
        def wrapper_fn(*args, **kwargs):
            start_time = time.time()
            result = original_fn(*args, **kwargs)
            end_time = time.time()
            print(f"Working Time [{original_fn.__name__}]: {end_time - start_time}")
            return result
    
        return wrapper_fn
    
    
    @time_log
    def list_append():
        a = list(range(100000))
        a2 = list()
        for i in a:
            a2.append(i * 2)
        print(a2[99999])
    
    
    @time_log
    def list_map():
        a = list(range(100000))
        a2 = list(map(lambda n: n * 2, a))
        print(a2[99999])
    
    
    @time_log
    def list_comprehension():
        a2 = [x * 2 for x in range(100000)]
        print(a2[99999])
    
    
    list_append()
    list_map()
    list_comprehension()
    199998
    Working Time [list_append]: 0.018465518951416016
    199998
    Working Time [list_map]: 0.018465757369995117
    199998
    Working Time [list_comprehension]: 0.011977434158325195

     

    리스트 컴프리헨션은 a list를 생성하지 않으니 좀 더 공평한 조건으로 비교를 해보자. 

    @time_log
    def list_append():
        a2 = list()
        for i in range(100000):
            a2.append(i * 2)
        print(a2[99999])
    
    
    @time_log
    def list_map():
        a2 = list(map(lambda n: n * 2, range(100000)))
        print(a2[99999])
    
    
    @time_log
    def list_comprehension():
        a2 = [x * 2 for x in range(100000)]
        print(a2[99999])
    
    
    list_append()
    list_map()
    list_comprehension()
    199998
    Working Time [list_append]: 0.01746678352355957
    199998
    Working Time [list_map]: 0.017966508865356445
    199998
    Working Time [list_comprehension]: 0.012975931167602539
    반응형
Designed by Tistory.