需求:求整数型数组int array[10000001]所有元素之和,统计计算部分的开销
验证平台:ThinkPad T450, Ubuntu 16.04
方法一:使用CPU暴力计算
代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 10000001
int64_t getClockTimeUs() {
struct timespec ts;
if(clock_gettime(CLOCK_MONOTONIC,&ts) == 0){
return ts.tv_sec * 1000000LL + ts.tv_nsec/1000L;
}
return 0;
}
int main() {
int *src = (int *)malloc(N * sizeof(int));
int result;
for(int i = 0; i < N; i++) src[i] = 1;
int64_t start = getClockTimeUs();
for(int k = 0; k < N; k++) {
result += src[k];
}
int64_t end = getClockTimeUs();
printf("result %d, cost %ld ms\n", result, (end - start)/1000L);
}
编译:
gcc sum_by_cpu.c -o sum_cpu
运行结果:
result 10000001, cost 29 ms
方法二:使用OpenMP计算
代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <omp.h>
#define N 10000001
int64_t getClockTimeUs() {
struct timespec ts;
if(clock_gettime(CLOCK_MONOTONI