Skip to content

Instantly share code, notes, and snippets.

@rsaporta
Forked from hadley/comments.r
Created December 1, 2012 18:31
Show Gist options
  • Save rsaporta/4183852 to your computer and use it in GitHub Desktop.
Save rsaporta/4183852 to your computer and use it in GitHub Desktop.
Time each line of execution in R
comments <- function(refs) {
srcfile <- attr(refs[[1]], "srcfile")
# first_line, first_byte, last_line, last_byte
com <- vector("list", length(refs))
for(i in seq_along(refs)) {
# Comments begin after last line of last block, and continue to
# first line of this block
if (i == 1) {
first_byte <- 1
first_line <- 1
} else {
first_byte <- refs[[i - 1]][4] + 1
first_line <- refs[[i - 1]][3]
}
last_line <- refs[[i]][1]
last_byte <- refs[[i]][2] - 1
if (last_byte == 0) {
if (last_line == 1) {
first_byte <- 0
last_byte <- 0
last_line <- 1
} else {
last_line <- last_line - 1
last_byte <- 1e3
}
}
lloc <- c(first_line, first_byte, last_line, last_byte)
com[[i]] <- srcref(srcfile, lloc)
}
com
}
library(stringr)
source("comments.r")
time_comment <- function(x) {
if (is.null(x)) return("")
if (x[3] == 0) return("")
out <- sprintf("%.3f", x[1:3])
names(out) <- c("user", "system", "elapsed")
out <- capture.output(print(noquote(out)))
str_c("#: ", out, collapse = "\n")
}
comment_ref <- function(x) {
if (x[1] == 1 && x[4] == 0) return("")
str_c(c(as.character(x), ""), collapse = "\n")
}
time_file <- function(path) {
lines <- readLines(path)
# Remove any line starting with #:
lines <- lines[!str_detect(lines, "^#:")]
# Parse file, and capture comments.
parsed <- parse(text = lines)
refs <- attr(parsed, "srcref")
comments <- comments(refs)
env <- new.env(parent = globalenv())
out <- vector("list", length(refs) * 3)
for(i in seq_along(refs)) {
t <- system.time(eval(parsed[[i]], env))
call <- parsed[[i]][[1]]
if (identical(call, as.name("{"))) t <- NULL
out[[3 * (i - 1) + 1]] <- comment_ref(comments[[i]])
out[[3 * (i - 1) + 2]] <- str_c(c(as.character(refs[[i]]), ""), collapse = "\n")
out[[3 * (i - 1) + 3]] <- time_comment(t)
}
out <- unlist(out)
out <- out[out != ""]
cat(str_c(out, collapse = ""), "\n", file = path)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment