diff options
| author | _Tradam <[email protected]> | 2023-09-08 01:29:47 +0000 |
|---|---|---|
| committer | GitHub <[email protected]> | 2023-09-08 01:29:47 +0000 |
| commit | 3c76c7f3d5db3f9586a90d03f8fbb02d79de9acd (patch) | |
| tree | afbe4b540967223911f7c5de36559b82154f02f3 /misc/examples/algorithms/random.c | |
| parent | 0841165881871ee01b782129be681209aeed2423 (diff) | |
| parent | 1a72205fe05c2375cfd380dd8381a8460d9ed8d1 (diff) | |
| download | STC-modified-modified.tar.gz STC-modified-modified.zip | |
Diffstat (limited to 'misc/examples/algorithms/random.c')
| -rw-r--r-- | misc/examples/algorithms/random.c | 42 |
1 files changed, 42 insertions, 0 deletions
diff --git a/misc/examples/algorithms/random.c b/misc/examples/algorithms/random.c new file mode 100644 index 00000000..e457d329 --- /dev/null +++ b/misc/examples/algorithms/random.c @@ -0,0 +1,42 @@ +#include <stdio.h> +#include <time.h> +#include <stc/crand.h> + +int main(void) +{ + const long long N = 10000000, range = 1000000; + const uint64_t seed = (uint64_t)time(NULL); + crand_t rng = crand_init(seed); + clock_t t; + + printf("Compare speed of full and unbiased ranged random numbers...\n"); + long long sum = 0; + t = clock(); + c_forrange (N) { + sum += (int32_t)crand_u64(&rng); + } + t = clock() - t; + printf("full range\t\t: %f secs, %lld, avg: %f\n", + (double)t/CLOCKS_PER_SEC, N, (double)(sum/N)); + + crand_uniform_t dist1 = crand_uniform_init(0, range); + rng = crand_init(seed); + sum = 0; + t = clock(); + c_forrange (N) { + sum += crand_uniform(&rng, &dist1); // unbiased + } + t = clock() - t; + printf("unbiased 0-%lld\t: %f secs, %lld, avg: %f\n", + range, (double)t/CLOCKS_PER_SEC, N, (double)(sum/N)); + + sum = 0; + rng = crand_init(seed); + t = clock(); + c_forrange (N) { + sum += (int32_t)crand_u64(&rng) % (range + 1); // biased + } + t = clock() - t; + printf("biased 0-%lld \t: %f secs, %lld, avg: %f\n", + range, (double)t/CLOCKS_PER_SEC, N, (double)(sum/N)); +} |
