From 93dd105707d9a7e681254c3913d22b3ff547b8cc Mon Sep 17 00:00:00 2001 From: Marvin Wright Date: Wed, 6 Dec 2023 20:47:58 +0100 Subject: [PATCH] default to 2 threads but give a startup message --- R/onAttach.R | 18 ++++++++++++++++++ R/predict.R | 2 +- R/ranger.R | 2 +- 3 files changed, 20 insertions(+), 2 deletions(-) create mode 100644 R/onAttach.R diff --git a/R/onAttach.R b/R/onAttach.R new file mode 100644 index 00000000..3f098998 --- /dev/null +++ b/R/onAttach.R @@ -0,0 +1,18 @@ + +.onAttach = function(libname, pkgname) { + if (!interactive()) { + return() + } + + threads_option <- getOption("ranger.num.threads") + threads_env <- Sys.getenv("R_RANGER_NUM_THREADS") + if (!is.null(threads_option)) { + thread_string <- paste(threads_option, "threads (set by options(ranger.num.threads = N).") + } else if (threads_env != "") { + thread_string <- paste(threads_env, "threads (set by environment variable 'R_RANGER_NUM_THREADS').") + } else { + thread_string <- "2 threads (default). Change with num.threads in ranger() and predict(), options(ranger.num.threads = N) or environment variable 'R_RANGER_NUM_THREADS'." + } + + packageStartupMessage(paste("ranger", packageVersion("ranger"), "using", thread_string)) +} diff --git a/R/predict.R b/R/predict.R index 82599ab0..0530654b 100644 --- a/R/predict.R +++ b/R/predict.R @@ -193,7 +193,7 @@ predict.ranger.forest <- function(object, data, predict.all = FALSE, ## Num threads ## Default 0 -> detect from system in C++. if (is.null(num.threads)) { - num.threads = 0 + num.threads <- as.integer(Sys.getenv("R_RANGER_NUM_THREADS", getOption("ranger.num.threads", 2L))) } else if (!is.numeric(num.threads) || num.threads < 0) { stop("Error: Invalid value for num.threads") } diff --git a/R/ranger.R b/R/ranger.R index 6d56d4d4..dc4dd823 100644 --- a/R/ranger.R +++ b/R/ranger.R @@ -514,7 +514,7 @@ ranger <- function(formula = NULL, data = NULL, num.trees = 500, mtry = NULL, ## Num threads ## Default 0 -> detect from system in C++. if (is.null(num.threads)) { - num.threads = 0 + num.threads <- as.integer(Sys.getenv("R_RANGER_NUM_THREADS", getOption("ranger.num.threads", 2L))) } else if (!is.numeric(num.threads) || num.threads < 0) { stop("Error: Invalid value for num.threads") }