Why does loading this file take up so much memory?

Trying to upload a file in python. This is a very large file (1.5Gb), but I have available memory, and I just want to do it once (hence the use of python, I just need to sort the file once so that python is a simple choice).

My problem is that downloading this file leads to a way to make a lot of memory use. When I loaded about 10% of the lines into memory, Python already uses 700Mb, which is obviously too much. At about 50%, the script freezes using 3.03 Gb of real memory (and slowly rising).

I know that this is not the most efficient method for sorting a file (from memory), but I just want it to work, so I can move on to more important problems: D So, what's wrong with the following python code which leads to massive memory usage :

print 'Loading file into memory'
input_file = open(input_file_name, 'r')
input_file.readline() # Toss out the header
lines = []
totalLines = 31164015.0
currentLine = 0.0
printEvery100000 = 0
for line in input_file:
    currentLine += 1.0
    lined = line.split('\t')
    printEvery100000 += 1
    if printEvery100000 == 100000:
        print str(currentLine / totalLines)
        printEvery100000 = 0;
    lines.append( (lined[timestamp_pos].strip(), lined[personID_pos].strip(), lined[x_pos].strip(), lined[y_pos].strip()) )
input_file.close()
print 'Done loading file into memory'

EDIT: , - , , , , , , . "" : 1) readLines(), , . , 1.7Gb. , lines.sort(), , , int. , . overhad : D

+5
2

, , . , Python , .

9.1 GB , , , :

  • 1,5
  • 31,164,015
  • 4

:

import sys
def sizeof(lst):
    return sys.getsizeof(lst) + sum(sys.getsizeof(v) for v in lst)

GIG = 1024**3
file_size = 1.5 * GIG
lines = 31164015
num_cols = 4
avg_line_len = int(file_size / float(lines))

val = 'a' * (avg_line_len / num_cols)
lst = [val] * num_cols

line_size = sizeof(lst)
print 'avg line size: %d bytes' % line_size
print 'approx. memory needed: %.1f GB' % ((line_size * lines) / float(GIG))

:

avg line size: 312 bytes
approx. memory needed: 9.1 GB
+3

, , . , ( , [ ]). Mmap , Linux ( ).

, , , , , , , , , .

, .

, :

import os
from mmap import mmap

input_file = open('unsorted.txt', 'r')
output_file = open('sorted.txt', 'w+')

# need to provide something in order to be able to mmap the file
# so we'll just copy the first line over
output_file.write(input_file.readline())
output_file.flush()
mm = mmap(output_file.fileno(), os.stat(output_file.name).st_size)
cur_size = mm.size()

for line in input_file:
  mm.seek(0)
  tup = line.split("\t")
  while True:
    cur_loc = mm.tell()
    o_line = mm.readline()
    o_tup = o_line.split("\t")
    if o_line == '' or tup[0] < o_tup[0]: # EOF or we found our spot
      mm.resize(cur_size + len(line))
      mm[cur_loc+len(line):] = mm[cur_loc:cur_size]
      mm[cur_loc:cur_loc+len(line)] = line
      cur_size += len(line)
      break
+1

All Articles