Mercurial > hg > Members > innparusu > openMP_examples
changeset 0:b8c472c04dc9
Add twice.c
author | innparusu |
---|---|
date | Sat, 03 Feb 2018 23:34:56 +0900 |
parents | |
children | 3b9c253ce087 |
files | twice.c |
diffstat | 1 files changed, 51 insertions(+), 0 deletions(-) [+] |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/twice.c Sat Feb 03 23:34:56 2018 +0900 @@ -0,0 +1,51 @@ +#include <stdio.h> +#include <string.h> +#include <stdlib.h> +#include <omp.h> +#include <sys/time.h> + +int length = 1024; +int cpu_num = 1; +void init(int argc, const char* argv[]) { + for (int i = 1; argv[i]; ++i) { + if (strcmp(argv[i], "-cpu") == 0) + cpu_num = (int)atoi(argv[i+1]); + else if (strcmp(argv[i], "-l") == 0) + length = (int)atoi(argv[i+1]); + } +} + +int main(int argc, const char* argv[]) +{ + int n; + init(argc, argv); + omp_set_num_threads(cpu_num); + int *a; + a = (int *) malloc(sizeof(int) * length); + for (int i = 0; i < length; i++) + { + a[i] = i; + } + + struct timeval tv; + gettimeofday(&tv, NULL); + double now = tv.tv_sec + (double)tv.tv_usec*1e-6; + +#pragma omp parallel for + for(int i = 0; i < length; i++) + { + a[i] = a[i] * 2; + } + + gettimeofday(&tv, NULL); + printf("%0.6f\n", (tv.tv_sec+(double)tv.tv_usec*1e-6) - now); + + for(int i = 0; i < length; i++) + { + if(a[i] != i*2) { + printf("fail\n"); + } + } + + return 0; +}