0

私は例を持っています:

    for line in IN.readlines():
        line = line.rstrip('\n')
        mas = line.split('\t')
        row = ( int(mas[0]), int(mas[1]), mas[2], mas[3], mas[4] )
        self.inetnums.append(row)
    IN.close()

ffilesize == 120mb の場合、スクリプト時間 = 10 秒。今回は減らせますか?

4

2 に答える 2

4

を取り外しますreadlines()

やるだけ

for line in IN:

あなたを使用readlinesして、ファイルからすべての行のリストを作成し、次に各行にアクセスしますが、これを行う必要はありません。それがなければ、 for ループは、ファイルから毎回行を返すジェネレーターを使用するだけです。

于 2012-04-05T10:32:01.153 に答える
2

リスト内包表記を使用すると、速度が向上する場合があります

inetnums=[(int(x) for x in line.rstrip('\n').split('\t')) for line in fin]

これは、2 つの異なるバージョンのプロファイル情報です。

>>> def foo2():
    fin.seek(0)
    inetnums=[]
    for line in fin:
        line = line.rstrip('\n')
        mas = line.split('\t')
        row = ( int(mas[0]), int(mas[1]), mas[2], mas[3])
        inetnums.append(row)


>>> def foo1():
    fin.seek(0)
    inetnums=[[int(x) for x in line.rstrip('\n').split('\t')] for line in fin]

>>> cProfile.run("foo1()")
         444 function calls in 0.004 CPU seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.003    0.003    0.004    0.004 <pyshell#362>:1(foo1)
        1    0.000    0.000    0.004    0.004 <string>:1(<module>)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
      220    0.000    0.000    0.000    0.000 {method 'rstrip' of 'str' objects}
        1    0.000    0.000    0.000    0.000 {method 'seek' of 'file' objects}
      220    0.000    0.000    0.000    0.000 {method 'split' of 'str' objects}


>>> cProfile.run("foo2()")
         664 function calls in 0.006 CPU seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.005    0.005    0.006    0.006 <pyshell#360>:1(foo2)
        1    0.000    0.000    0.006    0.006 <string>:1(<module>)
      220    0.000    0.000    0.000    0.000 {method 'append' of 'list' objects}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
      220    0.001    0.000    0.001    0.000 {method 'rstrip' of 'str' objects}
        1    0.000    0.000    0.000    0.000 {method 'seek' of 'file' objects}
      220    0.001    0.000    0.001    0.000 {method 'split' of 'str' objects}


>>> 
于 2012-04-05T10:56:33.833 に答える