Skip to content

Instantly share code, notes, and snippets.

@perdacherMartin
Created February 18, 2013 16:35
Show Gist options
  • Select an option

  • Save perdacherMartin/4978645 to your computer and use it in GitHub Desktop.

Select an option

Save perdacherMartin/4978645 to your computer and use it in GitHub Desktop.
serial jacobi example
#include <stdio.h>
#include <sys/time.h>
#define N 100
#define MAX_ITER 5000
typedef float MATRIX_V[N+1][N+1];
int timeval_subtract(struct timeval *result, struct timeval *t2, struct timeval *t1);
int main(int argc, char* argv) {
int i,j,k;
MATRIX_V V, V_tmp;
struct timeval start, end, diff;
float *p_local, *p_local_tmp, *swap;
// get starting time
gettimeofday(&start, NULL);
// initialize all points with reasonable starting values for the potential
for (i = 1; i < N; i++)
for (j = 1; j < N; j++)
V[i][j] = 51.0;
// boundary conditions
for (j = 0; j <= N; j++) V[0][j] = 30; /// left/
for (j = 0; j <= N; j++) V[N][j] = 70; /// right/
for (i = 0; i <= N; i++) V[i][0] = 0; /// bottom/
for (i = 0; i <= N; i++) V[i][N] = 100; /// top/
p_local=&V[0][0];
p_local_tmp=&V_tmp[0][0];
// numerically solve Laplace's equation
for (k = 0; k < MAX_ITER; k++) {
// calculate new values
for (i = 1; i < N; i++){
for (j = 1; j < N; j++){
*(p_local_tmp+i*N+j) = 0.25 * ( *(p_local+((i-1)*N)+j) + *(p_local+((i+1)*N)+j) +
*(p_local+(i*N)+j-1) + *(p_local+(i*N)+j+1));
}
}
// copy array
swap = p_local_tmp;
p_local_tmp = p_local;
p_local = swap;
}
// get end time
gettimeofday(&end, NULL);
timeval_subtract(&diff, &end, &start);
printf("Time used in seconds: %ld.%06ld;%d\n", diff.tv_sec, diff.tv_usec,N);
}
int timeval_subtract(struct timeval *result, struct timeval *t2, struct timeval *t1)
{
long int diff = (t2->tv_usec + 1000000 * t2->tv_sec) - (t1->tv_usec + 1000000 * t1->tv_sec);
result->tv_sec = diff / 1000000;
result->tv_usec = diff % 1000000;
return (diff<0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment