#include <stdio.h>
#include <arrayfire.h>
using namespace af;
static int samples = 20e6;
static double pi_gpu()
{
array x = randu(samples,f32), y = randu(samples,f32);
return 4.0 * sum<float>((mul(x, x) + mul(y, y)) < 1) / samples;
}
static double pi_cpu()
{
int count = 0;
for (int i = 0; i < samples; ++i) {
float x = float(rand()) / RAND_MAX;
float y = float(rand()) / RAND_MAX;
if (sqrt(x*x + y*y) < 1)
count++;
}
return 4.0 * count / samples;
}
static void gpu_wrapper() { pi_gpu(); }
static void cpu_wrapper() { pi_cpu(); }
int main(int argc, char ** argv)
{
try {
printf("gpu: %.5f seconds to estimate pi = %.5f\n", timeit(gpu_wrapper), pi_gpu());
printf("cpu: %.5f seconds to estimate pi = %.5f\n", timeit(cpu_wrapper), pi_cpu());
} catch (exception& e) {
fprintf(stderr, "%s\n", e.what());
}
#ifdef WIN32 // pause in Windows
if (!(argc == 2 && argv[1][0] == '-')) {
printf("hit [enter]...");
getchar();
}
#endif
return 0;
}