378 Accelerating MATLAB
®
Performance
We can now rewrite the example code from §7.3.1 using OpenMP constructs. Notice how
compact and easy-to-understand the new algorithm looks:
#include <mex.h>
#include <omp.h>
#include <gmp.h>
/* parallel compute function */
void do_calculation(unsigned *g_in, mxArray *g_out, unsigned n_thids)
{
// start parallel section with n_thids threads
#pragma omp parallel num_threads(n_thids)
{
int tid = omp_get_thread_num();
long tid = (long)t; // get this thread's ID
unsigned *in = g_in + tid*2; // and the inputs 'n' and 'k'
mpz_t z; // initialize a GMP large integer
mpz_init(z);
// calculate binomial coefficient
mpz_bin_uiui(z, (unsigned long)in[0], (unsigned long)in[1]);
// estimate the ...