Daniel Hermon
Daniel Hermon

Reputation: 61

Fastest way to find if a number is in range

I try to write a piece of code that takes a square image and apply a sharpen kernel.

I did manage to succeed in my task but I was disappointed by the running times of my program. The time it takes to blur an image and sharpen it (500x500) takes about 16 ms, I want to go lower than that, I used callgrind and cachegrind and I do see my cache miss is pretty low (About 3%) so as I tried to narrow down the problem I notices that every time I apply the kernel on a pixel I ask the follow if any of the channels is in range of [0,255]. I would like to know if there is a fast way to calculate if number is in range so far I use the following macros:

#define max(a, b) ((a) > (b) ? (a) : (b))
#define min(a, b) ((a) < (b) ? (a) : (b))

My pixel struct:

typedef struct {
    unsigned char red;
    unsigned char green;
    unsigned char blue;
} pixel;

and my calculation:

//p is a struct of pixel.
p.red = min(max(sumRed, 0), 255);
p.green = min(max(sumGreen, 0), 255);
p.blue = min(max(sumBlue, 0), 255);

Upvotes: 0

Views: 112

Answers (1)

chqrlie
chqrlie

Reputation: 144780

You are actually looking for a fast way to clamp values within a given range.

If you know the maximum range the values can take, which can probably be determined from the algorithm used, you can use a lookup table with an offset:

// clamp_table is a table of unsigned char of size maxvalue - minvalue + 1
// initialized this way:
unsigned char clamp_table[maxvalue - minvalue + 1];
for (size_t i = minvalue; i < 0; i++) {
    clamp_table[i - minvalue] = 0;
}
for (size_t i = 0; i < 256; i++) {
    clamp_table[i - minvalue] = i;
}
for (size_t i = 256; i <= maxvalue; i++) {
    clamp_table[i - minvalue] = 255;
}

// clamping becomes a simple table indirection:
r.red = clamp_table[sumRed - minvalue];
r.green = clamp_table[sumGreen - minvalue];
r.blue = clamp_table[sumBlue - minvalue];

minvalue and maxvalue should be known at compile time, clamp_table can then be made a statically initialized const array for improved performance.

Upvotes: 3

Related Questions