The first call to set_float_zero() will invoke float_zero_is_all_bits_zero() to determine how 0.0 is actually represented; it then uses memset() if it's safe, and falls back to an explicit loop if it isn't. On calls after the first, it merely checks a single flag.
This is useful if the memset() is significantly faster than the explicit loop, something that is not at all obvious.
The code: -
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
static int float_zero_is_all_bits_zero(void)
{
float f = 0.0;
unsigned char zero_bytes[sizeof f] = { 0 };
return memcmp(&f, zero_bytes, sizeof f) == 0;
}
void set_float_zero(float *dest, size_t count)
{
static int initialized = 0;
int may_use_memset;
if (!initialized) {
may_use_memset = float_zero_is_all_bits_zero();
initialized = 1;
}
if (may_use_memset) {
memset(dest, 0, count * sizeof *dest);
}
else {
size_t i;
for (i = 0; i < count; i ++) {
dest[i] = 0.0;
}
}
}
#define ARR_LEN 1000
int main(void)
{
float *arr = (float*)malloc(ARR_LEN * sizeof *arr);
set_float_zero(arr, ARR_LEN);
return 0;
}
Pradyut
http://pradyut.tk
http://spaces.msn.com/members/oop-edge/
http://groups-beta.google.com/group/oop_programming
No comments:
Post a Comment