Last active
July 20, 2023 06:37
-
-
Save larspontoppidan/1846920096b336a8a94f68d7f1d90f46 to your computer and use it in GitHub Desktop.
Timing test of Python print formatting methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import timeit | |
import sys | |
print("Python", sys.version) | |
def test1(p1:int, p2:float, p3:str): | |
return 'A typical: {:d} format {:.2f} example {:s}'.format(p1, p2, p3) | |
def test2(p1:int, p2:float, p3:str): | |
return 'A typical: %d format %.2f example %s' % (p1, p2, p3) | |
def test3(p1:int, p2:float, p3:str): | |
return f'A typical: {p1:d} format {p2:.2f} example {p3:s}' | |
def test4(p1:int, p2:float, p3:str): | |
return "A typical: " + str(p1) + " format " + str(round(p2, 2)) + " example " + p3 | |
p1 = 1324 | |
p2 = 3.4567 | |
p3 = "including a string" | |
ret = test1(p1, p2, p3) | |
assert test2(p1, p2, p3) == ret | |
assert test3(p1, p2, p3) == ret | |
assert test4(p1, p2, p3) == ret | |
print("Return value: " + ret) | |
print('format: ', timeit.timeit("test1(p1, p2, p3)", globals=globals())) | |
print('%: ', timeit.timeit("test2(p1, p2, p3)", globals=globals())) | |
print('f-string: ', timeit.timeit("test3(p1, p2, p3)", globals=globals())) | |
print('concat: ', timeit.timeit("test4(p1, p2, p3)", globals=globals())) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment