# Overhead cost of a function call

## Overhead cost of a function call

Overhead cost of a function call: Recently, I would like to apply unit testing method to my R program. The first thing i need to chop every few lines of the code into functions so that I can test each of them.

A Question comes up to my mind: What is the overhead cost of a function call? To answer this question, i wrote the following :

 123456789101112131415161718192021 `library``(rbenchmark)``library``(compiler)``f<-``function``(x,y){``    ``x+y``}``g<-``function``(x,y){``   ``f``(x,y)``}``cmpf<-``cmpfun``(f)``cmpg<-``cmpfun``(g)``benchmark``(1+2,``f``(1,2),``g``(1,2),``cmpf``(1,2),``cmpg``(1,2),``cmpg2``(1,2), replications =1000000, columns = ``c``(``"test"``, ``"replications"``, ``"elapsed"``, ``"relative"``),order=``'relative'``)``          ``test replications elapsed relative``1       1 + 2      1000000    4.00    1.000``4  ``cmpf``(1, 2)      1000000    4.34    1.085``2     ``f``(1, 2)      1000000    4.82    1.205``5  ``cmpg``(1, 2)      1000000    5.44    1.360``3     ``g``(1, 2)      1000000    5.68    1.420`

The result suggests several things

1. The overhead cost is about 0.82 second for 1,000,000 times function call.
2. If we compile the function, the overhead cost is about 0.34 second for 1,000,000 times function call.

I don’t know whether it is a huge cost, but I believe the benefit of cleaner writing code with unit testing must worth more than that!

TszKin Julian Chan

## Costo indirecto de una llamada de función

Overhead cost of a function call: recientemente, me gustaría aplicar el método de prueba de unidad a mi programa R. Lo primero que necesito es cortar cada pocas líneas del código en funciones para poder probar cada una de ellas.

Una pregunta me viene a la mente: ¿Cuál es el costo general de una llamada de función? Para responder a esta pregunta, escribí lo siguiente:

 123456789101112131415161718192021 `library``(rbenchmark)``library``(compiler)``f<-``function``(x,y){``    ``x+y``}``g<-``function``(x,y){``   ``f``(x,y)``}``cmpf<-``cmpfun``(f)``cmpg<-``cmpfun``(g)``benchmark``(1+2,``f``(1,2),``g``(1,2),``cmpf``(1,2),``cmpg``(1,2),``cmpg2``(1,2), replications =1000000, columns = ``c``(``"test"``, ``"replications"``, ``"elapsed"``, ``"relative"``),order=``'relative'``)``          ``test replications elapsed relative``1       1 + 2      1000000    4.00    1.000``4  ``cmpf``(1, 2)      1000000    4.34    1.085``2     ``f``(1, 2)      1000000    4.82    1.205``5  ``cmpg``(1, 2)      1000000    5.44    1.360``3     ``g``(1, 2)      1000000    5.68    1.420`