1.OpenMP
#include <stdio.h>
#include <omp.h>
#include <stdlib.h>
#include<iostream>
#include <chrono>
#include <chrono>
#include <ctime>
//g++ -fopenmp for_test.cpp -o f
int main(void) {
// Some computation here
long sum = 0;
double time_cost = 0;
// 1.define data
int array_len=100000;
int array_a[array_len];
int array_b[array_len];
int array_c[array_len];
//2.ini data
for(int i=0;i<array_len;++i)
{
array_a[i]=i;
array_b[i]=10;
array_c[i]=0;
}
auto start = std::chrono::system_clock::now();
//#pragma omp parallel for-----------------------------------------use or not use openmp
//for(int i=0;i<10000;++i)//1G
{
//#pragma omp parallel for reduction(+:sum)
for (int i=1; i<=array_len; i++) {
array_c[i]=array_a[i]*array_b[i];
}
}
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end-start;
std::time_t end_time = std::chrono::system_clock::to_time_t(end);
std::cout << "finished computation at " << std::ctime(&end_time)
<< "elapsed time: " << elapsed_seconds.count() << "s"
<< std::endl;
// for(int i=0;i<array_len;++i)
// printf("Sum:%d\n", array_c[i]);
return 0;
}
without openmp time cost
without openmp cpu load
with openmp time cost
with openmp cpu load
2 Neon
#include <iostream>
#include <arm_neon.h> //需包含的头文件
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#include <stdlib.h>
#include <chrono>
#include <chrono>
#include <ctime>
#include <cstring>
using namespace std;
#include<time.h>
void add_int_c(int* dst, int* src1, int* src2, int count)
{
int i;
for (i = 0; i < count; i++)
dst[i] = src1[i] + src2[i];
}
void add_int_neon(int* dst, int* src1, int* src2, int count)
{
int i;
for (i = 0; i < count; i += 4)
{
int32x4_t in1, in2, out;
in1 = vld1q_s32(src1);
src1 += 4;
in2 = vld1q_s32(src2);
src2 += 4;
out = vaddq_s32(in1, in2);
vst1q_s32(dst, out);
dst += 4;
}
}
int main()
{
/* 数据内存分配,初始化 */
int size =100000;//
int *dst = (int*)malloc(size * sizeof(int));
int *src1 = (int*)malloc(size * sizeof(int));
int *src2 = (int*)malloc(size * sizeof(int));
// int dst[size];
// int src1[size];
// int src2[size];
for(int i = 0; i < size; i++)
{
src1[i] = i;
src2[i] = i;
}
/* 时间初始化 */
struct timespec time1_img = {0, 0};
struct timespec time2_img = {0, 0};
clock_gettime(CLOCK_REALTIME, &time1_img);
// for(int i=0;i<40;++i)
{
for(int i = 0; i < size; i++)
{
add_int_c(dst, src1, src2, size);
}
}
clock_gettime(CLOCK_REALTIME, &time2_img);
printf("C time:%d ms\n", (time2_img.tv_sec - time1_img.tv_sec)*1000 + (time2_img.tv_nsec - time1_img.tv_nsec)/1000000);
printf("dst[0]:%d\n", dst[0]);
memset(dst, 0, size);
clock_gettime(CLOCK_REALTIME, &time1_img);
//for(int i=0;i<40;++i)
{
for(int i = 0; i < size; i++)
{
add_int_neon(dst, src1, src2, size);
}
}
clock_gettime(CLOCK_REALTIME, &time2_img);
printf("Neon time:%d ms\n", (time2_img.tv_sec - time1_img.tv_sec)*1000 + (time2_img.tv_nsec - time1_img.tv_nsec)/1000000);
printf("dst[0]:%d\n", dst[0]);
free(dst);
free(src1);
free(src2);
return 0;
}