4 ms·
A comment about: printing tab-aligned tables without str.join: # Python 3 print(*array, sep='\t') print(batch, epoch, loss, accuracy, time, sep='\t')
by eesmith 9y ago
A comment about:
printing tab-aligned tables without str.join:
# Python 3
print(*array, sep='\t')
print(batch, epoch, loss, accuracy, time, sep='\t')
During performance optimization of some print-heavy data generation code, I have had to switch code which used print(sep="\t") back to using str.join(). Consider:
import time
import tempfile
import random
data = [[str(random.random()) for i in range(10)] for j in range(10000)]
def print_join(out):
for row in data:
out.write("\t".join(row) + "\n")
def print_file(out):
for row in data:
print(*row, file=out, sep="\t")
def run(f):
with open("timing_data.txt", "w") as out:
t1 = time.time()
for loop in range(10):
f(out)
t2 = time.time()
print(f.__name__, t2-t1)
run(print_join)
run(print_file)
I get:
print_join 0.19790196418762207
print_file 0.7166078090667725
That is, str.join() takes less than 1/3 of the time as sep="\t".