0

If I have a long range of different functions, and I dont know which is responsible for the long processing time, how would be a good method to measure how long time each function is operating?`

For example, the help in aggregate (sf package) requires a lot of computations. I could just write system.time() before each, but would be nice if there were a smarter way, for example if I could get system.time per row or somthing similar.

m1 = cbind(c(0, 0, 1, 0), c(0, 1, 1, 0))
m2 = cbind(c(0, 1, 1, 0), c(0, 0, 1, 0))
pol = st_sfc(st_polygon(list(m1)), st_polygon(list(m2)))
set.seed(1985)
d = data.frame(matrix(runif(15), ncol = 3))
p = st_as_sf(x = d, coords = 1:2)
plot(pol)
plot(p, add = TRUE)
(p_ag1 = aggregate(p, pol, mean))
plot(p_ag1) # geometry same as pol
# works when x overlaps multiple objects in 'by':
p_buff = st_buffer(p, 0.2)
plot(p_buff, add = TRUE)
(p_ag2 = aggregate(p_buff, pol, mean)) # increased mean of second
# with non-matching features
m3 = cbind(c(0, 0, -0.1, 0), c(0, 0.1, 0.1, 0))
pol = st_sfc(st_polygon(list(m3)), st_polygon(list(m1)), st_polygon(list(m2)))
(p_ag3 = aggregate(p, pol, mean))
plot(p_ag3)
# In case we need to pass an argument to the join function:
(p_ag4 = aggregate(p, pol, mean, 
     join = function(x, y) st_is_within_distance(x, y, dist = 0.3)))
Jeppe Olsen
  • 968
  • 8
  • 19
  • 2
    You might want to use `profvis` (check [this post](https://stackoverflow.com/questions/6262203/measuring-function-execution-time-in-r), I guess it's a duplicate to yours). `profvis` gives an interactive report with statistics on each code line you submit. Just run `profvis::profvis({ # your code })` – pogibas Mar 29 '19 at 07:55
  • You could also read in detail about it here. [Profiling with RStudio](https://support.rstudio.com/hc/en-us/articles/218221837-Profiling-with-RStudio) – Ronak Shah Mar 29 '19 at 07:59

1 Answers1

1

This function will run each line of a code separately and return the sys.time if you pass it a c/p string of your code

sys.time.perrow <- function(str)
{
list <- strsplit(str,"\n")[[1]]
times <- sapply(list,function(line)
  {
  time <- system.time(eval(parse(text=line)))
  return(time)
},simplify=F,USE.NAMES = T)
return(times)
}

Please note: Multiline arguments will break this code. I would have to think about something more sophisticated for that.

Julian_Hn
  • 2,086
  • 1
  • 8
  • 18