0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Python リストの足し算 速度比較

Last updated at Posted at 2022-05-24

概要

足し算をする際に、どの方法が早いか比較してみた。

数値は全て、Decimal型とした。

test1 test2 test3 test4
forループで+=する reduceとlambda reduceとadd sum
import time
from functools import wraps, reduce
from operator import add
from decimal import Decimal

def stop_watch(func):
    @wraps(func)
    def wrapper(*args, **kargs):
        # 処理開始直前の時間
        start = time.monotonic()

        # 処理実行
        result = func(*args, **kargs)

        # 処理終了直後の時間から処理時間を算出
        elapsed_time = time.monotonic() - start

        # 処理時間を出力
        print("{} ms in {}".format(elapsed_time * 1000, func.__name__))
        return result
    return wrapper
    
a =[Decimal("5.325")*i for i in range(1, 10000)]

@stop_watch
def test1(lst):
    total = 0
    for d in lst:
        total += d
    print(total, type(total))
    
@stop_watch
def test2(lst):
    total = reduce(lambda x, y: x + y, lst)
    print(total, type(total))
    
@stop_watch
def test3(lst):
    total = reduce(add, lst)
    print(total, type(total))
    
@stop_watch
def test4(lst):
    total = sum(lst)
    print(total, type(total))

test1(a)
test2(a)
test3(a)
test4(a)

実行結果

266223375.000 <class 'decimal.Decimal'>
0.7629496976733208 ms in test1
266223375.000 <class 'decimal.Decimal'>
1.1549443006515503 ms in test2
266223375.000 <class 'decimal.Decimal'>
0.7026819512248039 ms in test3
266223375.000 <class 'decimal.Decimal'>
0.6021261215209961 ms in test4

基本的にはsum関数を使用するのが一番早い結果となった。
リストが小さいときはreduce,addが早いことも確認したがほとんど差なし

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?