2
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のListの作成速度調査

Last updated at Posted at 2022-03-26

始めに

最近AtCoderを始めたのですが、なかなか処理速度を考えて処理を書くまでには至らず、
書き方ごとの処理速度に関する当たりをつけるため、とりあえずよくあるリスト作成の速度を調査してみた。

検証するケース

1 - forループでinfをN個持ったリストを作成

import time

def cal_for_inf(count):
  start = time.perf_counter()
  inf = float('inf')
  arr = [inf for i in range(count)]
  end = time.perf_counter()
  return end-start

2 - *でinfをN個持ったリストを作成

def cal_multi_inf(count):
  start = time.perf_counter()
  inf = float('inf')
  arr = [inf] * count
  end = time.perf_counter()
  return end-start

3 - forループで0をN個持ったリストを作成

def cal_for_zero(count):
  start = time.perf_counter()
  arr = [0 for i in range(count)]
  end = time.perf_counter()
  return end-start

4 - *でinfをN個持ったリストを作成

def cal_multi_zero(count):
  start = time.perf_counter()
  arr = [0] * count
  end = time.perf_counter()
  return end-start

検証

検証したデータはpandasのDataFrameに入れて確認する

import pandas as pd
count = 1000000 ## 作成するListの要素数
data = pd.DataFrame(
  [[
    cal_for_inf(count),
    cal_multi_inf(count),
    cal_for_zero(count),
    cal_multi_zero(count)
  ] for i in range(1,1001)],
  columns=["cal_for_inf","cal_multi_inf","cal_for_zero","cal_multi_zero"]
)

検証結果

data.describe()
cal_for_inf cal_multi_inf cal_for_zero cal_multi_zero
count 1000.000000 1000.000000 1000.000000 1000.000000
mean 0.029765 0.003394 0.029859 0.003449
std 0.002517 0.001754 0.002755 0.001216
min 0.024995 0.002467 0.025293 0.002451
25% 0.028420 0.002672 0.028401 0.002722
50% 0.029345 0.002796 0.029270 0.002853
75% 0.030675 0.003115 0.030712 0.003177
max 0.060927 0.045249 0.053833 0.008475

スクリーンショット 2022-03-26 13.47.03.png

結論

中に入れるものが一定なのであれば*で入れたほうが早い。

2
0
1

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
2
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?