Skip to content

Commit da6bf71

Browse files
committed
Improve generation of random decimal128s
1 parent 95608e1 commit da6bf71

File tree

1 file changed

+39
-1
lines changed

1 file changed

+39
-1
lines changed

test/benchmark_libbid.c

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -119,13 +119,51 @@ __attribute__ ((noinline)) void test_comparisons_64(Decimal64* data, const char*
119119
printf("Comparisons <%-10s >: %-10" PRIu64 " us (s=%zu)\n", label, elapsed_time_us, s);
120120
}
121121

122+
Decimal128 random_decimal128(void)
123+
{
124+
char str[64]; // Plenty of room for: -d.dddddddddddddddddddddddddddddddddE±eeee
125+
126+
// 1. Random sign (50/50)
127+
char sign = (random_uint64() & 1) ? '-' : '+';
128+
129+
// 2. Random 34-digit significand
130+
char digits[35];
131+
for (int i = 0; i < 34; i++)
132+
{
133+
digits[i] = '0' + (random_uint64() % 10);
134+
}
135+
136+
// Ensure first digit is non-zero (avoid leading zeros affecting value)
137+
if (digits[0] == '0')
138+
{
139+
digits[0] = '1' + (random_uint64() % 9);
140+
}
141+
digits[34] = '\0';
142+
143+
// 3. Random exponent: -6143 to +6144
144+
int exp_range = 6144 - (-6143) + 1; // 12288 possible values
145+
int exponent = (int)(random_uint64() % exp_range) - 6143;
146+
147+
// 4. Build string: "±D.DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDE±EEEE"
148+
snprintf(str, sizeof(str), "%c%c.%sE%+d",
149+
sign,
150+
digits[0], // integer part (1 digit)
151+
&digits[1], // fractional part (33 digits)
152+
exponent);
153+
154+
// 5. Parse to decimal128
155+
_IDEC_flags flags = 0;
156+
Decimal128 result = bid128_from_string(str, &flags);
157+
158+
return result;
159+
}
122160

123161
__attribute__ ((__noinline__)) void generate_vector_128(Decimal128* buffer, size_t buffer_len)
124162
{
125163
size_t i = 0;
126164
while (i < buffer_len)
127165
{
128-
buffer[i] = bid128_from_uint64(random_uint64());
166+
buffer[i] = random_decimal128();
129167
++i;
130168
}
131169
}

0 commit comments

Comments
 (0)