现在的集成开发环境很好的支持了市面上的多数多核CPU,比如在intel双核CPU的系统上安装好vs2008后,
第一,在项目属性-c++-语言中选择支持openmp
第二,在环境变量中加入OMP_NUM_THREADS变量赋值2
可以了,打开vs2008,新建一个console程序。
敲入下面的例子,相信我们都能看懂的:
- /************************************************************************/
- /* 利用Monte Carlo算法求圆周率pi */
- /************************************************************************/
- #include <iostream>
- #include <stdio.h>
- #include <cmath>
- #include <ctime>
- #include <omp.h>
- #include <time.h>
- using namespace std;
- #define pear 5000000 //扔的“黄豆”数目
- int isInCir(double x,double y)
- {
- if ((x * x + y * y) <= 1)
- {
- return 1; //在1/4园内的话,返1
- }
- return 0;
- }
- int main()
- {
- float kaishi;
- float jieshu;
- int i;
- int num = 0;//在园内的豆豆数目
- double x, y;
- double mianji;
- srand((unsigned)time(NULL));
- kaishi = clock();
- // singer
- int singerNum = 0;
- for (i = 0; i < pear; i++)
- {
- x = rand() % RAND_MAX / float(RAND_MAX);
- y = rand() % RAND_MAX / float(RAND_MAX);
- if (isInCir(x, y) == 1)
- {
- singerNum++;
- }
- }
- jieshu = clock();
- cout << "单核处理时间为:" << jieshu - kaishi << endl;
- //双核2线程
- kaishi = clock();
- omp_set_num_threads(2);
- #pragma omp parallel for reduction(+ : num)
- for (i = 0; i < pear; i++)
- {
- x = rand() % RAND_MAX / float(RAND_MAX);
- y = rand() % RAND_MAX / float(RAND_MAX);
- if (isInCir(x, y) == 1)
- {
- num++;
- }
- }
- jieshu = clock();
- cout << "双核两个线程处理时间为:" << jieshu-kaishi<<endl;
- //双核3-200线程
- int moreNum = 0;
- for(int j = 3; j < 200;j = j + 20){
- moreNum = 0;
- kaishi = clock();
- omp_set_num_threads(j);
- #pragma omp parallel for reduction(+ : moreNum)
- for (i = 0; i < pear; i++)
- {
- x = rand() % RAND_MAX / float(RAND_MAX);
- y = rand() % RAND_MAX / float(RAND_MAX);
- if (isInCir(x, y) == 1)
- {
- moreNum++;
- }
- }
- jieshu = clock();
- cout << "双核" << j << "个线程处理时间为:" << jieshu - kaishi << endl;
- }
- cout << "豆豆落在园内的个数:" << num << endl;
- cout << "最大随机数:" << RAND_MAX << endl;
- mianji = (num * 1.0) / pear;
- //printf("Monte Carlo算法模拟出的半径为一的1/4圆的面积为%f\n", mianji);
- cout << "Monte Carlo算法模拟出的半径为一的1/4圆的面积为" << mianji << endl;
- cout << "计算出的pi值为:" << 4 * mianji << endl;
- return 0;
- }