rmicrobenchmark

Understanding and comparing execution times of various computations


  1. In the first comparison, r sqrt(5)^2has better mean timing compared to r sqrt(5^2). Why is this happening?

  2. In the second comparison the above is reversed. I have tried it with more number of iterations (times). Finding it difficult to understand what is going on.

microbenchmark::microbenchmark(sqrt(5)^2,sqrt(5^2), times = 1e3)
#> Unit: nanoseconds
#>       expr min  lq    mean median  uq   max neval cld
#>  sqrt(5)^2 144 151 210.705    162 169  6304  1000  a 
#>  sqrt(5^2) 148 157 269.604    169 226 25936  1000   b
microbenchmark::microbenchmark(sqrt(5)^2,sqrt(5^2), log(exp(5)), times = 1e3)
#> Unit: nanoseconds
#>         expr min  lq    mean median  uq  max neval cld
#>    sqrt(5)^2 145 168 193.956    180 184 3059  1000   a
#>    sqrt(5^2) 149 159 189.753    170 176 3778  1000   a
#>  log(exp(5)) 132 147 183.599    154 166 8062  1000   a

Created on 2023-07-19 by the reprex package (v2.0.1)


Solution

  • Doesn't make much sense to compare with one input - 5. Try longer vector. We can see medians are consistent.

    x <- 1:10000
    
    microbenchmark::microbenchmark(sqrt(x)^2, sqrt(x^2), times = 10000)
    # Unit: microseconds
    #       expr  min   lq     mean median   uq     max neval cld
    #  sqrt(x)^2 29.0 51.6 95.77408   54.9 58.3 79210.8 10000  a 
    #  sqrt(x^2) 35.4 47.0 61.64323   48.8 52.0  8017.2 10000   b
    
    microbenchmark::microbenchmark(sqrt(x)^2, sqrt(x^2), log(exp(x)), times = 10000)
    # Unit: microseconds
    #         expr   min     lq      mean median    uq     max neval cld
    #    sqrt(x)^2  28.2  52.25 100.85237   56.1  60.4 80131.9 10000  a 
    #    sqrt(x^2)  35.4  47.70  57.88721   49.7  53.5  4441.1 10000  a 
    #  log(exp(x)) 162.1 196.90 262.39865  202.4 220.5 83254.2 10000   b