I wrote this function a while back:
def faster_print(*args, sep=" ", end="\n", file=stdout):
file.write(sep.join(map(str, args))+end)
and I tested it:
from sys import stdout
from time import perf_counter
def faster_print(*args, sep=" ", end="\n", file=stdout):
file.write(sep.join(map(str, args))+end)
def time(function, *args, **kwargs):
start = perf_counter()
function(*args, **kwargs)
return perf_counter()-start
def using_normal_print(number):
for i in range(number):
print("Hello world.", 5, 5.0, ..., str)
def using_faster_print(number):
for i in range(number):
faster_print("Hello world.", 5, 5.0, ..., str)
normal_time = time(using_normal_print, number=100)
faster_time = time(using_faster_print, number=100)
print("Normal print:", normal_time)
print("My print function", faster_time)
It turns out that it is only faster in IDLE and not cmd. I know that IDLE creates its own objects for sys.stdout, sys.stdin and sys.stderr but I don't get why it only slows down python's built in print function. This answer says that the built in print function is written in c. Shouldn't that make it faster as my function needs to be compiled from python bytecode into machine code?
I am using Python 3.7.9 and IDLE version 3.7.9
datetime.now()is not necessarily accurate for this purpose; you should usetime.perf_counteras this "a clock with the highest available resolution to measure a short duration", or rather than rolling your own timing code you could use thetimeitmodule.datetime.now(). You should usetime.process_timeinstead.