算法
Eratosthenes
OpenMP
OpenMP是用于共享内存并行系统的多线程程序设计的一套指导性的编译处理方案;OpenMP支持的编程语言包括C语言,C++和Fortan;OpenMP支持的编译器包括Sun Compiler,GNU Compiler和Intel Compiler等;
(一)OpenMP包括编译制导语句,运行时库函数以及环境变量:
- 编译制导语句:以#pragma omp开头的编译语句;
- 运行时库函数:提供的API接口函数在omp.h头文件中声明;
- 环境变量:灵活控制程序的运行;
3.编译命令:g++/gcc -fopenmp 源文件
(二)编译制导语句
1.#pragma omp parallel :后续语句开启多个线程执行(默认与cpu核数量一致);
2.#pragma omp parallel for:后续紧跟的for循环开启多线程执行;
(三)运行时库函数
1.omp_get_num_procs():获取内核数量;
2.omp_get_thread_num():获取线程id;
(四)环境变量
1.OMP_NUM_THREADS:表示开启线程数量;
程序
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <iostream>
#include <sys/time.h>
#include <cassert>
#include <omp.h>
using namespace std;
typedef unsigned int uint32;
typedef unsigned long long int uint64;
inline void sieve(uint64 start, uint64 end, uint64& num, int threadNum) {
assert(start>1);
bool* a = new bool[end + 1];
memset(a + 2, true,end + 1);
#pragma omp parallel for num_threads(threadNum)
for (uint64 i = 2; i <= (uint64)sqrt(end); i++) {
if (a[i])
for (uint64 j = i; i*j <= end; j++)
a[i*j] = false;
}
uint64 prime_num=0;
if(start==2)
prime_num++;
#pragma omp parallel for num_threads(threadNum) reduction(+: prime_num)
for (uint64 i =(start%2==0?start+1:start); i <=end ;i += 2) {
if (a[i])
prime_num++;
}
num=prime_num;
delete[] a;
}
int main(int argc, char* argv[]) {
if(argc != 4){
fprintf(stderr, "usage: Eratosthenes start_number end_number threadNum\n");
exit(-1);
}
struct timeval ts,te;
uint64 start = atoi(argv[1]);
uint64 end = atoi(argv[2]);
int threadNum = atoi(argv[3]);
uint64 num = 0;
gettimeofday(&ts, NULL);
sieve(start, end, num, threadNum);
gettimeofday(&te, NULL);
cout << "count: " << num << endl;
cout << "total time: " << ((te.tv_sec - ts.tv_sec) * 1000 + (te.tv_usec - ts.tv_usec) / 1000) << "ms" << endl;
getchar();
return 0;
}
运行结果
与个人电脑性能有关