Speed up scripts – find a faster function (Zonal Statistics)

In the first post of the “Speed Up Your Script” series, we showed you how to use the underlying R tools to determine the execution time of a particular part of a script. In doing so, we learned that the sf library loads shapefiles faster than the older rgdal.

Today we will try to speed up the simple task of extracting averages from a raster (image from Sentinel 2) for a grid of 100 polygons with a 10m radius circle shape.

Of course, the easiest way to do this is to use the extract function we know from the raster library. However, for a large number of objects, this tool is not very effective, so we will additionally use the function:

At the end we will check which function is the fastest.

We will start by loading libraries that we will use:

Load data:

The data looks like this:

To evaluate which function runs faster, we will use the microbenchmark library:

For the velox library, we need to convert the grid to velox format:

We write the line of code responsible for the test:

We execute and wait for the result:

The extract function we have been using so far turned out to be 44 times slower than exact_extract and 4 times slower than the function from the velox library. The comparison shows that the other functions we are using for our task are much more efficient, which will significantly reduce our computation time. So remember that in order to optimize our script, it is worth investing some time to look for a faster solution 🙂 We don’t like to wait long, so today we invite you to the next post about speeding up scripts.

Leave a Reply

Your email address will not be published.

Translate using Google Translate»
Social media & sharing icons powered by UltimatelySocial

Podoba Ci się nasza strona? Odwiedź nasz profil