Skip to content

Commit

Permalink
Merge pull request #78 from aitap/openmp_fixes
Browse files Browse the repository at this point in the history
Fixes for OpenMP limit options and detection
  • Loading branch information
dselivanov authored Feb 16, 2025
2 parents 695d4eb + 36a3ccd commit 147d400
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 16 deletions.
24 changes: 10 additions & 14 deletions R/zzz.R
Original file line number Diff line number Diff line change
Expand Up @@ -9,22 +9,24 @@


.onAttach = function(libname, pkgname) {
n_omp_threads = detect_number_omp_threads()
n_omp_threads = getOption("rsparse_omp_threads")
if (is.null(n_omp_threads)) { # unlikely given .onLoad below
n_omp_threads = detect_number_omp_threads()
options("rsparse_omp_threads" = n_omp_threads)
}
if (interactive()) {
msg = paste0("Setting OpenMP threads number to ",
msg = paste0("Number of OpenMP threads set to ",
n_omp_threads,
"\nCan be adjusted by setting `options(\"rsparse_omp_threads\" = N_THREADS)`")
packageStartupMessage(msg)
}

options("rsparse_omp_threads" = n_omp_threads)

}

.onLoad = function(libname, pkgname) {
# install_name_tool_change_float()
# library.dynam("rsparse", pkgname, libname)
options("rsparse_omp_threads" = detect_number_omp_threads())
if (is.null(getOption("rsparse_omp_threads")))
options("rsparse_omp_threads" = detect_number_omp_threads())
logger = lgr::get_logger('rsparse')
logger$set_threshold('info')
assign('logger', logger, envir = parent.env(environment()))
Expand All @@ -37,14 +39,8 @@
#'
#' @export
detect_number_omp_threads = function() {
n_omp_threads = as.numeric(Sys.getenv("OMP_NUM_THREADS"))
if (is.na(n_omp_threads) || n_omp_threads <= 0) n_omp_threads = omp_thread_count()
## if OMP_THREAD_LIMIT is set, maximize on that limit.
omp_thread_limit = as.numeric(Sys.getenv("OMP_THREAD_LIMIT"))
if ( is.na(omp_thread_limit) ) omp_thread_limit = n_omp_threads
n_omp_threads = min(omp_thread_limit, n_omp_threads)

n_omp_threads
# now respects both OMP_NUM_THREADS and OMP_THREAD_LIMIT
omp_thread_count()
}

install_name_tool_change_float = function() {
Expand Down
4 changes: 2 additions & 2 deletions src/utils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,9 @@ dMappedCSC extract_mapped_csc(Rcpp::S4 input) {
int omp_thread_count() {
int n = 0;
#ifdef _OPENMP
#pragma omp parallel reduction(+ : n)
int max_threads = omp_get_max_threads(), thread_limit = omp_get_thread_limit();
n = max_threads < thread_limit ? max_threads : thread_limit;
#endif
n += 1;
return n;
}

Expand Down

0 comments on commit 147d400

Please sign in to comment.