web-dev-qa-db-ja.com

Python-初期容量のリストを作成します

このようなコードは頻繁に発生します:

l = []
while foo:
    #baz
    l.append(bar)
    #qux

リストに何千もの要素を追加しようとしている場合、リストは新しい要素に合わせて絶えずサイズ変更する必要があるため、これは本当に遅いです。

Javaでは、初期容量を持つArrayListを作成できます。あなたのリストがどれほど大きくなるかを知っているなら、これははるかに効率的です。

このようなコードは、多くの場合、リスト内包表記にリファクタリングできることを理解しています。ただし、for/whileループが非常に複雑な場合、これは実行不可能です。 Pythonプログラマに相当するものはありますか?

175
Claudiu
def doAppend( size=10000 ):
    result = []
    for i in range(size):
        message= "some unique object %d" % ( i, )
        result.append(message)
    return result

def doAllocate( size=10000 ):
    result=size*[None]
    for i in range(size):
        message= "some unique object %d" % ( i, )
        result[i]= message
    return result

結果。 (各機能を144回評価し、期間を平均します)

simple append 0.0102
pre-allocate  0.0098

結論。それはほとんど問題ではありません。

早すぎる最適化はすべての悪の根源です。

119
S.Lott

Pythonリストには組み込みの事前割り当てがありません。本当にリストを作成する必要があり、追加のオーバーヘッドを回避する必要がある場合(そして確認する必要があります)、これを行うことができます:

l = [None] * 1000 # Make a list of 1000 None's
for i in xrange(1000):
    # baz
    l[i] = bar
    # qux

おそらく、代わりにジェネレーターを使用してリストを回避できます。

def my_things():
    while foo:
        #baz
        yield bar
        #qux

for thing in my_things():
    # do something with thing

この方法では、リストはすべてメモリにすべて保存されるわけではなく、必要に応じて生成されるだけです。

73
Ned Batchelder

ショートバージョン:使用

pre_allocated_list = [None] * size

リストを事前に割り当てます(つまり、リストを追加してリストを徐々に形成する代わりに、リストの「サイズ」要素をアドレス指定できるようにします)。この操作は、大きなリストであっても非常に高速です。後でリスト要素に割り当てられる新しいオブジェクトを割り当てると、はるかに時間がかかり、パフォーマンスの面でプログラムのボトルネックになります。

ロングバージョン:

初期化時間を考慮する必要があると思います。 pythonではすべてが参照であるため、各要素をNoneまたは何らかの文字列に設定するかどうかは関係ありません-いずれにしても、それは単なる参照です。ただし、参照する要素ごとに新しいオブジェクトを作成する場合は時間がかかります。

Python 3.2の場合:

import time
import copy

def print_timing (func):
  def wrapper (*arg):
    t1 = time.time ()
    res = func (*arg)
    t2 = time.time ()
    print ("{} took {} ms".format (func.__name__, (t2 - t1) * 1000.0))
    return res

  return wrapper

@print_timing
def prealloc_array (size, init = None, cp = True, cpmethod=copy.deepcopy, cpargs=(), use_num = False):
  result = [None] * size
  if init is not None:
    if cp:
      for i in range (size):
          result[i] = init
    else:
      if use_num:
        for i in range (size):
            result[i] = cpmethod (i)
      else:
        for i in range (size):
            result[i] = cpmethod (cpargs)
  return result

@print_timing
def prealloc_array_by_appending (size):
  result = []
  for i in range (size):
    result.append (None)
  return result

@print_timing
def prealloc_array_by_extending (size):
  result = []
  none_list = [None]
  for i in range (size):
    result.extend (none_list)
  return result

def main ():
  n = 1000000
  x = prealloc_array_by_appending(n)
  y = prealloc_array_by_extending(n)
  a = prealloc_array(n, None)
  b = prealloc_array(n, "content", True)
  c = prealloc_array(n, "content", False, "some object {}".format, ("blah"), False)
  d = prealloc_array(n, "content", False, "some object {}".format, None, True)
  e = prealloc_array(n, "content", False, copy.deepcopy, "a", False)
  f = prealloc_array(n, "content", False, copy.deepcopy, (), False)
  g = prealloc_array(n, "content", False, copy.deepcopy, [], False)

  print ("x[5] = {}".format (x[5]))
  print ("y[5] = {}".format (y[5]))
  print ("a[5] = {}".format (a[5]))
  print ("b[5] = {}".format (b[5]))
  print ("c[5] = {}".format (c[5]))
  print ("d[5] = {}".format (d[5]))
  print ("e[5] = {}".format (e[5]))
  print ("f[5] = {}".format (f[5]))
  print ("g[5] = {}".format (g[5]))

if __== '__main__':
  main()

評価:

prealloc_array_by_appending took 118.00003051757812 ms
prealloc_array_by_extending took 102.99992561340332 ms
prealloc_array took 3.000020980834961 ms
prealloc_array took 49.00002479553223 ms
prealloc_array took 316.9999122619629 ms
prealloc_array took 473.00004959106445 ms
prealloc_array took 1677.9999732971191 ms
prealloc_array took 2729.999780654907 ms
prealloc_array took 3001.999855041504 ms
x[5] = None
y[5] = None
a[5] = None
b[5] = content
c[5] = some object blah
d[5] = some object 5
e[5] = a
f[5] = []
g[5] = ()

ご覧のとおり、同じNoneオブジェクトへの参照の大きなリストを作成するだけで、ほとんど時間がかかりません。

プリペンディングまたはエクステンドには時間がかかります(平均化はしませんでしたが、これを数回実行した後、エクステンドとアペンドにはほぼ同じ時間がかかることがわかります)。

各要素に新しいオブジェクトを割り当てる-それは最も時間がかかるものです。そして、S.Lottの答えはそれをします-毎回新しい文字列をフォーマットします。これは厳密には必要ありません-スペースを事前に割り当てたい場合は、Noneのリストを作成してから、リスト要素にデータを自由に割り当ててください。いずれにせよ、リストの作成中または作成後にリストを追加/拡張するよりも、リストの追加/拡張よりもデータの生成に時間がかかります。ただし、データがまばらなリストが必要な場合は、Noneのリストから開始する方が確実に高速です。

45
LRN

このためのPython的な方法は次のとおりです。

x = [None] * numElements

または、事前ポップしたいデフォルト値、たとえば.

bottles = [Beer()] * 99
sea = [Fish()] * many
vegetarianPizzas = [None] * peopleOrderingPizzaNotQuiche

[編集:Caveat Emptor[Beer()] * 99構文は、oneを作成しますBeerそして、同じ単一インスタンスへの99個の参照を配列に設定します]

Pythonのデフォルトのアプローチは非常に効率的ですが、要素の数を増やすと効率は低下します。

比較する

import time

class Timer(object):
    def __enter__(self):
        self.start = time.time()
        return self

    def __exit__(self, *args):
        end = time.time()
        secs = end - self.start
        msecs = secs * 1000  # millisecs
        print('%fms' % msecs)

Elements   = 100000
Iterations = 144

print('Elements: %d, Iterations: %d' % (Elements, Iterations))


def doAppend():
    result = []
    i = 0
    while i < Elements:
        result.append(i)
        i += 1

def doAllocate():
    result = [None] * Elements
    i = 0
    while i < Elements:
        result[i] = i
        i += 1

def doGenerator():
    return list(i for i in range(Elements))


def test(name, fn):
    print("%s: " % name, end="")
    with Timer() as t:
        x = 0
        while x < Iterations:
            fn()
            x += 1


test('doAppend', doAppend)
test('doAllocate', doAllocate)
test('doGenerator', doGenerator)

#include <vector>
typedef std::vector<unsigned int> Vec;

static const unsigned int Elements = 100000;
static const unsigned int Iterations = 144;

void doAppend()
{
    Vec v;
    for (unsigned int i = 0; i < Elements; ++i) {
        v.Push_back(i);
    }
}

void doReserve()
{
    Vec v;
    v.reserve(Elements);
    for (unsigned int i = 0; i < Elements; ++i) {
        v.Push_back(i);
    }
}

void doAllocate()
{
    Vec v;
    v.resize(Elements);
    for (unsigned int i = 0; i < Elements; ++i) {
        v[i] = i;
    }
}

#include <iostream>
#include <chrono>
using namespace std;

void test(const char* name, void(*fn)(void))
{
    cout << name << ": ";

    auto start = chrono::high_resolution_clock::now();
    for (unsigned int i = 0; i < Iterations; ++i) {
        fn();
    }
    auto end = chrono::high_resolution_clock::now();

    auto elapsed = end - start;
    cout << chrono::duration<double, milli>(elapsed).count() << "ms\n";
}

int main()
{
    cout << "Elements: " << Elements << ", Iterations: " << Iterations << '\n';

    test("doAppend", doAppend);
    test("doReserve", doReserve);
    test("doAllocate", doAllocate);
}

私のWindows 7 i7では、64ビットPythonは

Elements: 100000, Iterations: 144
doAppend: 3587.204933ms
doAllocate: 2701.154947ms
doGenerator: 1721.098185ms

C++は(MSVC、64ビット、最適化を有効にして構築)

Elements: 100000, Iterations: 144
doAppend: 74.0042ms
doReserve: 27.0015ms
doAllocate: 5.0003ms

C++デバッグビルドは以下を生成します。

Elements: 100000, Iterations: 144
doAppend: 2166.12ms
doReserve: 2082.12ms
doAllocate: 273.016ms

ここでのポイントは、Pythonを使用すると、パフォーマンスが7〜8%向上し、高性能アプリを作成していると思われる場合(または、 Webサービスなど)に気付かれることはありませんが、言語の選択を再考する必要があるかもしれません。

また、ここのPythonコードはPythonコードではありません。ここで真のPythonesqueコードに切り替えると、パフォーマンスが向上します。

import time

class Timer(object):
    def __enter__(self):
        self.start = time.time()
        return self

    def __exit__(self, *args):
        end = time.time()
        secs = end - self.start
        msecs = secs * 1000  # millisecs
        print('%fms' % msecs)

Elements   = 100000
Iterations = 144

print('Elements: %d, Iterations: %d' % (Elements, Iterations))


def doAppend():
    for x in range(Iterations):
        result = []
        for i in range(Elements):
            result.append(i)

def doAllocate():
    for x in range(Iterations):
        result = [None] * Elements
        for i in range(Elements):
            result[i] = i

def doGenerator():
    for x in range(Iterations):
        result = list(i for i in range(Elements))


def test(name, fn):
    print("%s: " % name, end="")
    with Timer() as t:
        fn()


test('doAppend', doAppend)
test('doAllocate', doAllocate)
test('doGenerator', doGenerator)

それは与える

Elements: 100000, Iterations: 144
doAppend: 2153.122902ms
doAllocate: 1346.076965ms
doGenerator: 1614.092112ms

(32ビットでは、doGeneratorはdoAllocateよりも優れています)。

ここで、doAppendとdoAllocateの間のギャップは非常に大きくなっています。

明らかに、ここでの違いは、これを数回以上実行している場合、またはこれらの数値が桁違いにスケールアウトされる負荷の高いシステムで実行している場合、またはかなり大きなリスト。

ここでのポイント:最高のパフォーマンスを得るためにPythonの方法で実行してください。

しかし、一般的な高レベルのパフォーマンスを心配している場合、Pythonは間違った言語です。最も基本的な問題は、Python関数呼び出しは、従来、デコレータなどのPython機能( https://wiki.python。 org/moin/PythonSpeed/PerformanceTips#Data_Aggregation#Data_Aggregation )。

22
kfsone

他の人が述べたように、NoneTypeオブジェクトを使用してリストを事前シードする最も簡単な方法。

そうは言っても、Pythonリストが実際に機能する方法を理解してから、これが必要であると判断する必要があります。リストのCPython実装では、基になる配列は常にオーバーヘッドサイズで作成され、( 4, 8, 16, 25, 35, 46, 58, 72, 88, 106, 126, 148, 173, 201, 233, 269, 309, 354, 405, 462, 526, 598, 679, 771, 874, 990, 1120, etc)のサイズが徐々に大きくなるため、リストのサイズ変更はそれほど頻繁に行われません。

この動作のために、mostlist.append()関数はO(1)付加の複雑さであり、これらの境界の1つを越えるときにのみ複雑さが増します。 、その時点で複雑さはO(n)になります。 S. Lottの答えでは、この動作が実行時間の最小の増加につながります。

ソース: http://www.laurentluce.com/posts/python-list-implementation/

8
Russell Troxel

@ s.lottのコードを実行し、事前割り当てによって同じ10%のパフォーマンスの向上を実現しました。ジェネレーターを使用して@jeremyのアイデアを試し、doAllocateよりもgenのパフォーマンスをよく見ることができました。私のプロジェクトでは、10%の改善が重要であるため、多くの人に感謝しています。

def doAppend( size=10000 ):
    result = []
    for i in range(size):
        message= "some unique object %d" % ( i, )
        result.append(message)
    return result

def doAllocate( size=10000 ):
    result=size*[None]
    for i in range(size):
        message= "some unique object %d" % ( i, )
        result[i]= message
    return result

def doGen( size=10000 ):
    return list("some unique object %d" % ( i, ) for i in xrange(size))

size=1000
@print_timing
def testAppend():
    for i in xrange(size):
        doAppend()

@print_timing
def testAlloc():
    for i in xrange(size):
        doAllocate()

@print_timing
def testGen():
    for i in xrange(size):
        doGen()


testAppend()
testAlloc()
testGen()

testAppend took 14440.000ms
testAlloc took 13580.000ms
testGen took 13430.000ms
4
Jason Wiener

Pythonの事前割り当てに関する懸念は、numpyを使用している場合に発生します。numpyには、Cのような配列がより多くあります。この場合、事前割り当ての懸念事項は、データの形状とデフォルト値です。

大規模なリストで数値計算を行っており、パフォーマンスが必要な場合は、numpyを検討してください。

3
J450n

一部のアプリケーションでは、辞書が探しているものです。たとえば、find_totientメソッドでは、ゼロインデックスがないため、辞書を使用する方が便利であることがわかりました。

def totient(n):
    totient = 0

    if n == 1:
        totient = 1
    else:
        for i in range(1, n):
            if math.gcd(i, n) == 1:
                totient += 1
    return totient

def find_totients(max):
    totients = dict()
    for i in range(1,max+1):
        totients[i] = totient(i)

    print('Totients:')
    for i in range(1,max+1):
        print(i,totients[i])

この問題は、事前に割り当てられたリストでも解決できます。

def find_totients(max):
    totients = None*(max+1)
    for i in range(1,max+1):
        totients[i] = totient(i)

    print('Totients:')
    for i in range(1,max+1):
        print(i,totients[i])

誤って間違って使用した場合に例外をスローする可能性のあるNoneを保存しているため、またマップで回避できるEdgeケースについて考える必要があるため、これはエレガントではなく、バグが発生しやすいと感じています。

辞書はそれほど効率的ではないのは確かですが、他の人がコメントしているように、small速度の違いはsignificantメンテナンスの危険性があるとは限りません。

0
Josiah Yoder