Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenMP Programming : How to specify the number of threads as a command line option

Tags:

openmp

I am running a local blastx server. One of the command line options is -num_threads. Looking at the executable, blastx, thinking it may be a shell script that sets OMP_NUM_THREADS, it turns out that it is in machine code. I am assuming (possibly incorrectly) that it is an OpenMP application and this got me thinking.

Question : is it possible to change the number of OpenMP threads as a command line option, as opposed to using the environmental variable OMP_NUM_THREADS?

like image 525
irritable_phd_syndrome Avatar asked Dec 21 '15 21:12

irritable_phd_syndrome


People also ask

How do you set the number of threads in OpenMP?

To set the number of threads to use in your program, set the environment variable OMP_NUM_THREADS . OMP_NUM_THREADS sets the number of threads used in OpenMP parallel regions defined in your own code, and within Arm Performance Libraries.

How many threads does OpenMP use?

The obvious drawback of the baseline implementation that we have is that it only uses one thread, and hence only one CPU core. To exploit all CPU cores, we must somehow create multiple threads of execution.


2 Answers

Using OpenMP, you have basically 3 different ways of specifying the number of threads to use in a parallel region:

  • The most commonly used one is the environment variable OMP_NUM_THREADS which needs to be set in the code's environment prior to running it for being effective;
  • The function omp_set_num_threads(), to be called before reaching a parallel region; and
  • The optional num_threads() clause of the parallel directive.

The relative priorities of these are defined in great details by the standard but pretty much boil down to num_threads() taking precedence over omp_set_num_threads(), which itself takes precedence over OMP_NUM_THREADS.

So now, if you want to have your code defining the number of OpenMP threads to use as a command line option, what you need is:

  1. To parse you command line, either by hand, or using a function like getopt, and to store the value you read in a variable; and
  2. To use this value in either a call to omp_set_num_threads() or as a parameter to the num_threads() clause. Either of the two will take precedence to the possible value set for OMP_NUM_THREADS.
like image 77
Gilles Avatar answered Oct 22 '22 09:10

Gilles


OMP_NUM_THREADS is parsed by the program at runtime, so it already does what you want.

Setting it at compile time has no effect (unless you specifically design your build system to use it).

Because you export this environment variable, it's there at runtime as well. That's why you think it is doing something when you compile.

like image 1
Jeff Hammond Avatar answered Oct 22 '22 11:10

Jeff Hammond