2

By profiling, I've determined that about 60% of my program's time is spent in writing to file, in the one line:

fout.write('%d\t%d\n' % (i, j))

Here i and j are integers. Two questions: would implementing this in Cython give me a significant speed gain, and how would I implement it in Cython? I'm having trouble finding examples of writing to files from Cython.

Regarding the last point, this line occurs in a function that is called by the rest of my program very often to dump output to a file, so I'd like to leave the file open between function calls, and pass in a file object rather than reopening the file in each call.

AatG
  • 685
  • 8
  • 23

1 Answers1

2

You can get a significant performance gain by sending to your hard drive a compacted amount of data, which can be achieved using numpy.savez_compressed(), or writting in binary format:

with open('name.output', 'wb') as fout:
    fout.write(data)

Cython uses the same functions to write files that Python does, accessed through the Python API, and therefore it should not make it faster.

Saullo G. P. Castro
  • 56,802
  • 26
  • 179
  • 234