[Tutor] Speeding up my Python program
Alan Gauld
alan.gauld at yahoo.co.uk
Mon Feb 7 18:30:39 EST 2022
On 07/02/2022 19:53, aj0358 at web.de wrote:
> I am looking for a way to speed up my python program.
The first thing to do is find out where the time is being spent.
Python has profiling tools but Pillow is written on C so will be very
fast so if the time is spent there you need to think about how to speed
it up.
For example you are grabbing the whole screen, it might be better to
only grab the area you need. That will reduce the work Pillow has
to do processing it.
In particular note the warning on the PixelAccess class documentation page:
"""
Accessing individual pixels is fairly slow. If you are looping over all
of the pixels in an image, there is likely a faster way using other
parts of the Pillow API.
"""
Also, do you need to call load() explicitly? If not it may be that
Pillow is calling it internally, thus doubling the work done.
> It contains a simple while-loop, a few print commands and some imports of
> the external libraries PIL and time:
> from PIL import ImageGrab
> import time
>
> while end_time < 1:
You never set end_time to an initial value, are you missing some code?
> start_time=time.time()
> rgb1 = ImageGrab.grab().load()[1185,561]
> rgb2 = ImageGrab.grab().load()[1260,568]
> rgb3 = ImageGrab.grab().load()[1331,571]
> print(rgb1)
> print(rgb2)
> print(rgb3)
> end_time=time.time()-start_time
> print(end_time)
>
> The goal is to analyse every frames of a video (60 fps) and to get the
> pixel colors of three pixels. Unfortunately, at the moment, the programm
> only analyses one frame every (about) 0.5 seconds.
You may be asking more of Pillow than it is capable of, it isn't really
designed for real-time video processing so far as I'm aware. There are
some video libraries around that may do this better, eg. cgkit might do
what you want.
Also the Blender community uses Python extensively and asking for
assistance there may throw up some other options.
> Now I am looking for a tool to speed up his specific program. Do You have
> any ideas which library or tool to use (I ve heard sth of cython and numpy
> but dont know how they work...)
I doubt if that is the best route here, I'm fairly sure almost all the
time is spent in the Pillow functions and they are already written in C...
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list