Last active
January 20, 2023 23:50
-
-
Save bukowa/cb25c3be843dd67d30e6c3b221bdf4e9 to your computer and use it in GitHub Desktop.
python pillow simple benchmark
This file contains hidden or 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 json | |
| import os.path | |
| import timeit | |
| from collections import namedtuple | |
| from PIL import Image | |
| SizeUnit = namedtuple('SizeUnit', ['size', 'name']) | |
| KB = SizeUnit(1024, 'KB') | |
| MB = SizeUnit(1024*1024, 'MB') | |
| def pretty_size(size, size_unit=KB): | |
| return '{:.3f} {}'.format(size / size_unit.size, size_unit.name) | |
| def run(input_name, output_name, op, **save_kwargs): | |
| data = { | |
| 'input_name': input_name, | |
| 'output_name': output_name, | |
| 'op': output_name, | |
| 'save_kwargs': save_kwargs, | |
| } | |
| def _run(): | |
| pre_size = os.path.getsize(input_name) | |
| img = Image.open(input_name) | |
| img = op(img) | |
| img.save(output_name, **save_kwargs) | |
| new_size = os.path.getsize(output_name) | |
| data['input_size'] = pretty_size(pre_size, MB) | |
| data['output_size'] = pretty_size(new_size, KB) | |
| data['time'] = '{:.4f} s'.format(timeit.timeit(_run, number=1)) | |
| print(json.dumps(data, indent='\t')) | |
| def thumbnail(img: Image): | |
| img.thumbnail((250, 250)) | |
| return img | |
| def noop(img): | |
| return img | |
| run('input.jpg', 'thumbnail.jpg', thumbnail) | |
| run('input.jpg', 'quality30.jpg', noop, quality=30) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment