# Times per second benchmark

**R snippets**, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

In GNU R the simplest way to measure execution time of a piece code is to use system.time. However, sometimes I want to find out how many times some function can be executed in one second. This is especially useful when we want to compare functions that have significantly different execution speed.

Fortunately times per second benchmark for execution time can be simply evaluated using the following snippet:

**<-**

**function**

**(**f, time

**)**

**{**

**()**

**<-**0

**<-**proc.time

**()[**3

**]**

**repeat**

**{**

**<-**i

**+**1

**(**i

**)**

**<-**proc.time

**()[**3

**]**

**if**

**(**stop

**–**start

**>**time

**)**

**{**

**(**i

**/**

**(**stop

**–**start

**))**

**}**

**}**

**}**

This function takes two parameters: a function to be benchmarked (f) and how much time is to be used for evaluation (time). It returns an estimate how many times per second function f can be executed.

As a simple application of tps function consider calculating relative speed of standard, lattice and ggplot2 graphics. The following function compares them by plotting histograms:

**(**ggplot2

**)**

**(**lattice

**)**

**<-**

**function**

**(**n, time

**)**

**{**

**<-**runif

**(**n

**)**

**<-**c

**(**tps

**(**

**function**

**(**i

**)**

**{**

**(**x, 10, main

**=**i

**)**

**}**, time

**)**,

**(**

**function**

**(**i

**)**

**{**

**(**histogram

**(**x, nbin

**=**10, main

**=**format

**(**i

**)))**

**}**, time

**)**,

**(**

**function**

**(**i

**)**

**{**

**(**qplot

**(**x, binwidth

**=**0.1, main

**=**i

**))**

**}**, time

**))**

**(**b

**)**

**<-**c

**(**“hist”, “histogram”, “qplot”

**)**

**(**b

**)**

**}**

The function takes two arguments. First is number of points to sample for the histogram and second is time passed to tps function. On my computer the test gave the following result for 10000 size of the sample and 5 seconds for each function each :

**(**10000, 5

**)**

We can see that standard hist is over 10 times faster than from histogram from lattice and almost 40 times faster than qplot from ggplot2.

**leave a comment**for the author, please follow the link and comment on their blog:

**R snippets**.

R-bloggers.com offers

**daily e-mail updates**about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.