I need to convert an array of floats, 500e6 long, to an ascii file. Doing this in a loop takes long time. I wander if there is a fast way for doing this.
I used a standard loop: NumSamples is 200e6; dataword is a vector of 200e6 values.
NumSamples=len(dataword)
for i in range(1,NumSamples):
MyAscii=str(dataword[i])+"\n"
fout.write(MyAscii)
python as language
Try batching writes, so that you don't call
fout.writeevery 4 bytes:This will only call
fout.writeonce every 1000 floats, at the cost of storing the string for 1000 floats in memory (negligible). As a rule of thumb, use the biggestBATCH_SIZEyou can get without running out of memory.Or, if you're using a Python version older than 3.12 that doesn't have
itertools.batched, here's a hand-rolled version: