| 1 |
|
| 2 |
|
| 3 |
""" |
| 4 |
Benchmark different terminal color libraries. |
| 5 |
""" |
| 6 |
|
| 7 |
from timeit import Timer |
| 8 |
|
| 9 |
|
| 10 |
def benchmark(stmt, n=1000, r=3): |
| 11 |
setup = ( |
| 12 |
"from ansimarkup import parse;" |
| 13 |
"from colorama import Style as S, Fore as F;" |
| 14 |
"from termcolor import colored;" |
| 15 |
"from plumbum import colors;" |
| 16 |
"from pastel import colorize;" |
| 17 |
"from rich.markup import render" |
| 18 |
) |
| 19 |
timer = Timer(stmt, setup=setup) |
| 20 |
best = min(timer.repeat(r, n)) |
| 21 |
|
| 22 |
usec = best * 1e6 / n |
| 23 |
return usec |
| 24 |
|
| 25 |
|
| 26 |
def run_tests(title, tests): |
| 27 |
print(title) |
| 28 |
results = sorted((benchmark(v), k) for k, v in tests.items()) |
| 29 |
for usec, name in results: |
| 30 |
print(" {:<12} {:01.4f} μs".format(name, usec)) |
| 31 |
print() |
| 32 |
|
| 33 |
|
| 34 |
tests_simple_1 = { |
| 35 |
"termcolor": 'colored("red bold", "red", attrs=["bold"])', |
| 36 |
"colorama": 'S.BRIGHT + F.RED + "red bold" + S.RESET_ALL', |
| 37 |
"ansimarkup": 'parse("<r><b>red bold</b></r>")', |
| 38 |
"pastel": 'colorize("<fg=red;options=bold>red bold</>")', |
| 39 |
"plumbum": 'colors.red | colors.bold | "red bold"', |
| 40 |
"rich": 'render("[bold red]red bold[/bold red]")', |
| 41 |
} |
| 42 |
|
| 43 |
tests_simple_2 = { |
| 44 |
"termcolor": 'colored("red bold", "red", attrs=["bold"]) + colored("red", "red") + colored("bold", attrs=["bold"])', |
| 45 |
"colorama": 'S.BRIGHT + F.RED + "red bold" + S.RESET_ALL + F.RED + "red" + S.RESET_ALL + S.BRIGHT + "bold" + S.RESET_ALL', |
| 46 |
"ansimarkup": 'parse("<r><b>red bold</b>red</r><b>bold</b>")', |
| 47 |
"pastel": 'colorize("<fg=red;options=bold>red bold</><fg=red>red</><options=bold>red</>")', |
| 48 |
"plumbum": '(colors.red + colors.bold | "red bold") + (colors.red | "red") + (colors.bold | "bold")', |
| 49 |
"rich": 'render("[red][bold]red bold[/bold]red[/red][bold]bold[/bold]")', |
| 50 |
} |
| 51 |
|
| 52 |
run_tests("Benchmark 1: <r><b>red bold</b></r>", tests_simple_1) |
| 53 |
run_tests("Benchmark 2: <r><b>red bold</b>red</r><b>bold</b>", tests_simple_2) |