one billion sum for cpp using Open MP (VS code)
程序员文章站
2022-04-01 16:52:37
...
sequential sum: 500000000500000000
sequential sum: 2.619 secs
parallel sum: 500000000500000000
parallel sum: 0.306 secs
speedup: 8.55
//MyTimer.cpp
using namespace std;
#include <iostream>
#include <chrono>
typedef std::chrono::high_resolution_clock Clock;
typedef std::chrono::time_point<Clock> mytime_type;
mytime_type start_time;
void timer_start(){
start_time = Clock::now();
}
double timer_end(){
mytime_type end_time = Clock::now();
return chrono::duration_cast<chrono::nanoseconds>(end_time - start_time).count()/1000/1000/1000.0;
}
// mysum.cpp
#include <omp.h>
#include <iostream>
#include <string>
#include <ctime>
using namespace std;
void sequentail_sum(const long loop_times){
long sum = 0;
for (long i = 0; i <= loop_times; i++)
sum+=i;
cout<<"sequential sum: "<<sum<<endl;
}
void parallel_sum(long range){
int cpu_num = 10;
omp_set_num_threads(cpu_num);
long i,sum=0;
#pragma omp parallel default(none) private(i) shared(range) reduction(+: sum)
{
int start = (range / omp_get_num_threads() * omp_get_thread_num());
int end = (range / omp_get_num_threads() * (omp_get_thread_num() + 1));
for (i = start; i < end; i++) {
sum += i;
// printf("TID : %d:, sum: %ld, i: %ld \n",omp_get_thread_num(),sum,i);
}
}
cout<<"parallel sum: "<<sum+range<<endl;
}
// main.cpp
#include <omp.h>
#include <iostream>
#include "mysum.cpp"
#include "MyTimer.cpp"
using namespace std;
int main()
{
long num = 1000000000; // 1 billion
timer_start();
sequentail_sum(num);
double sequential_time = timer_end();
cout << "sequential sum: " << sequential_time << " secs" << endl;
timer_start();
parallel_sum(num);
double parallel_time = timer_end();
cout << "parallel sum: " << parallel_time << " secs" << endl;
cout << "speedup: " << ((int)((sequential_time / parallel_time)*100))/100.0<< endl;
return 0;
}
tasks.json
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "build",
"type": "shell",
"command": "g++",
"args": [
"-g",
"${file}",
"-std=c++11",
"-fopenmp",
"-o",
"${fileBasenameNoExtension}.out"
],
"problemMatcher": [
"$gcc"
]
}
]
}
// launch.json
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "(gdb) Launch",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/main.out",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
}
]
}
// settings.json
{
"cmake.configureOnOpen": false
}
上一篇: Java parallel Bucket Sort
下一篇: Vue 之 组件传值