Speed up R scripts – check how long your code takes to run

The R language is constantly evolving. More and more new features are being developed and released. Some of them do the same as the ones created before, but in a shorter time. Technology is simply advancing 🙂

When writing or optimizing existing code, it is best to check if the solution we used/wrote is sometimes slower than another approach to the problem. We can do this with two tools implemented in Base R: Sys.time and system.time. Today we will show you how to use them. First, we will use functions from the rgdal and sf packages to check how fast vector data is loaded. We will load a layer with almost 600 thousand buildings from OSM project for Mazowieckie region:

Sys.time returns a specific time. To check the speed of the function, we first need to store the start time in a variable, say start_time, and then subtract the end time from the start time after executing the function/part of code. In our case, it will look like this:

Let’s look at how long each function takes to load the data:

Sf is over 8x faster 🙂

And how to use system.time. This function returns the runtime of the whole function. We can also create our function which contains part of the script and check how much it takes. This time we load the land use from OSM:

And we will write two functions:

And we write it to system.time:

The result of system.time looks like this:

This time sf managed to make it 10x faster.

Today we showed you how to use simple functions to measure the runtime of different parts of your code. As you can see, two functions do the same thing (load shp into R) in significantly different times. So we recommend you to test several solutions and sometimes write your own function that can run faster than the already developed one.

The world needs to evolve 🙂 Have fun optimizing

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