88 lines
2.2 KiB
C++
88 lines
2.2 KiB
C++
#include <cstdio>
|
|
#include <cstdlib>
|
|
#include <chrono>
|
|
#include <cassert>
|
|
#include "fastrand.h"
|
|
|
|
#define N 10000000
|
|
#define M 99999999 // M > N
|
|
#define FROM 100
|
|
#define TO 576
|
|
|
|
int main() {
|
|
assert(M > N); // M > N
|
|
|
|
// Init
|
|
srand((unsigned int)time(NULL));
|
|
rand_state rs = init_rand();
|
|
uint32_t sum = 0; // to avoid compiler optimizing out stuff
|
|
|
|
printf("Full range generation perf - %d number of cases:\n", N);
|
|
|
|
auto t0 = std::chrono::high_resolution_clock::now();
|
|
|
|
// rand
|
|
for (int i = 0; i < N; ++i) {
|
|
sum += rand();
|
|
}
|
|
|
|
auto t1 = std::chrono::high_resolution_clock::now();
|
|
|
|
// arc4
|
|
for (int i = 0; i < N; ++i) {
|
|
sum += arc4random();
|
|
}
|
|
|
|
auto t2 = std::chrono::high_resolution_clock::now();
|
|
|
|
// lcg
|
|
for (int i = 0; i < N; ++i) {
|
|
sum += lcg(&rs);
|
|
}
|
|
|
|
auto t3 = std::chrono::high_resolution_clock::now();
|
|
|
|
// results 1
|
|
|
|
auto rand_elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(t1 - t0);
|
|
auto arc4_elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(t2 - t1);
|
|
auto lcg_elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(t3 - t2);
|
|
|
|
printf("Time (rand): %.3f ms.\n", rand_elapsed.count() * 1e-6);
|
|
printf("Time (arc4): %.3f ms.\n", arc4_elapsed.count() * 1e-6);
|
|
printf("Time (lcg): %.3f ms.\n", lcg_elapsed.count() * 1e-6);
|
|
|
|
printf("Modulo VS nomod perf for rand_between (both LCG) - %d number of cases:\n", M);
|
|
|
|
auto t4 = std::chrono::high_resolution_clock::now();
|
|
|
|
// lcg + modulo
|
|
for (int i = 0; i < M; ++i) {
|
|
sum += FROM + (lcg(&rs) % (TO - FROM));
|
|
}
|
|
|
|
auto t5 = std::chrono::high_resolution_clock::now();
|
|
|
|
// rand_between (also LCG, but no modulus)
|
|
for (int i = 0; i < M; ++i) {
|
|
sum += rand_between(&rs, FROM, TO);
|
|
}
|
|
|
|
auto t6 = std::chrono::high_resolution_clock::now();
|
|
|
|
// results 2
|
|
|
|
auto mod_elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(t5 - t4);
|
|
auto between_elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(t6 - t5);
|
|
|
|
uint32_t choice = rand_between(&rs, FROM, TO);
|
|
printf("lcg + modulo [%u, %u): %.3f ms.\n", FROM, TO, mod_elapsed.count() * 1e-6);
|
|
printf("rand_between [%u, %u): %.3f ms.\n", FROM, TO, between_elapsed.count() * 1e-6);
|
|
|
|
// checksum - avoid optimizing out loops
|
|
|
|
printf("Checksum: 0x%x\n", sum);
|
|
|
|
return 0;
|
|
}
|