Copy #include <stdio.h>
#include <omp.h>
#include <time.h>
#include <sys/time.h>
void test() {
int a = 0;
int i;
for(i=0; i<1000000000; i++) {
a++;
}
}
int main() {
struct timeval start, end;
gettimeofday(&start, NULL);
int i;
for(i=0; i<8; i++) {
test();
}
gettimeofday(&end, NULL);
printf("time = %f seconds\n", (double)((end.tv_sec * 1000000 + end.tv_usec)- (start.tv_sec * 1000000 + start.tv_usec))/1000000);
}
Copy # compile with gnu gcc
gcc -o serial serial.c -fopenmp
# compile with clang (on mac)
clang -Xpreprocessor -fopenmp serial.c -lomp -oserial
Copy $ ./serial
time = 20.059342 seconds
Now we use 4 (the default setting of my machine) threads to see how fast we can get!
Copy #include <stdio.h>
#include <omp.h>
#include <time.h>
#include <sys/time.h>
void test() {
int a = 0;
int i;
for(i=0; i<1000000000; i++) {
a++;
}
}
int main() {
struct timeval start, end;
gettimeofday(&start, NULL);
int i;
#pragma omp parallel for
for(i=0; i<8; i++) {
test();
}
gettimeofday(&end, NULL);
printf("time = %f seconds\n", (double)((end.tv_sec * 1000000 + end.tv_usec)- (start.tv_sec * 1000000 + start.tv_usec))/1000000);
}
Copy # compile with gnu gcc
gcc -o parallel parallel_with_openmp.c -fopenmp
# compile with clang (on mac)
clang -Xpreprocessor -fopenmp parallel_with_openmp.c -lomp -oparallel
Copy $ ./parallel
time = 5.337185 seconds
That's amazing! As I know when a biology scientist wants to calculate the structure of some proteins, it can even take him/her time-cost from months down to weeks!