Question: I need to optimize this smooth function to increase speeds using methods such as loop unrolling and blocking etc. The smoothing function takes as input
I need to optimize this smooth function to increase speeds using methods such as loop unrolling and blocking etc.
The smoothing function takes as input a source image src and returns the smoothed result in the destination image dst. The function avg returns the average of all the pixels around the (i,j)th pixel. Your task is to optimize smooth (and avg) to run as fast as possible. (Note: The function avg is a local function and you can get rid of it altogether to implement smooth in some other way.)
This is the original code with helper functions. THE CODE I NEED TO CHANGE IS THE SMOOTH METHOD - THE CODE I NEED TO CHANGE IS THE SMOOTH METHOD - THE CODE I NEED TO CHANGE IS THE SMOOTH METHOD - THE CODE I NEED TO CHANGE IS THE SMOOTH METHOD - THE CODE I NEED TO CHANGE IS THE SMOOTH METHOD
/* A struct used to compute averaged pixel value */ typedef struct { int red; int green; int blue; int num; } pixel_sum;
/* Compute min and max of two integers, respectively */ static int min(int a, int b) { return (a < b ? a : b); } static int max(int a, int b) { return (a > b ? a : b); }
/* * initialize_pixel_sum - Initializes all fields of sum to 0 */ static void initialize_pixel_sum(pixel_sum *sum) { sum->red = sum->green = sum->blue = 0; sum->num = 0; return; }
static void accumulate_sum(pixel_sum *sum, pixel p) { sum->red += (int) p.red; sum->green += (int) p.green; sum->blue += (int) p.blue; sum->num++; return; }
/* * assign_sum_to_pixel - Computes averaged pixel value in current_pixel */ static void assign_sum_to_pixel(pixel *current_pixel, pixel_sum sum) { current_pixel->red = (unsigned short) (sum.red/sum.num); current_pixel->green = (unsigned short) (sum.green/sum.num); current_pixel->blue = (unsigned short) (sum.blue/sum.num); return; }
/* * avg - Returns averaged pixel value at (i,j) */ static pixel avg(int dim, int i, int j, pixel *src) { int ii, jj; pixel_sum sum; pixel current_pixel;
initialize_pixel_sum(&sum); for(ii = max(i-1, 0); ii <= min(i+1, dim-1); ii++) for(jj = max(j-1, 0); jj <= min(j+1, dim-1); jj++) accumulate_sum(&sum, src[RIDX(ii, jj, dim)]);
assign_sum_to_pixel(¤t_pixel, sum); return current_pixel; }
char smooth_descr[] = "smooth: Current working version"; void smooth(int dim, pixel *src, pixel *dst) { int i, j;
for (i = 0; i < dim; i++) for (j = 0; j < dim; j++) dst[RIDX(i, j, dim)] = avg(dim, i, j, src);
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
