| 1 | #pragma once |
| 2 | |
| 3 | #if !defined(_WIN32) |
| 4 | #include <pthread.h> |
| 5 | #include <unistd.h> |
| 6 | #endif |
| 7 | |
| 8 | #include <cmath> |
| 9 | #include <cstdint> |
| 10 | #include <iostream> |
| 11 | #include <random> |
| 12 | #include <thread> |
| 13 | |
| 14 | #include "common.hpp" |
| 15 | #include "printf.h" |
| 16 | |
| 17 | #define SAMPLER_DETERMINISTIC 0 |
| 18 | #define SAMPLER_LOWDISCREPANCY 0 |
| 19 | |
| 20 | #include <stdio.h> |
| 21 | #include <time.h> |
| 22 | |
| 23 | #if SAMPLER_LOWDISCREPANCY |
| 24 | #include "lowdiscrepancy.hpp" |
| 25 | #endif |
| 26 | |
| 27 | template <uint64_t SAMPLE_RATE> |
| 28 | class Sampler { |
| 29 | private: |
| 30 | static constexpr double SAMPLE_PROBABILITY = |
| 31 | (double)1.0 / (double)SAMPLE_RATE; |
| 32 | |
| 33 | uint64_t _next; |
| 34 | #if !SAMPLER_DETERMINISTIC |
| 35 | #if !SAMPLER_LOWDISCREPANCY |
| 36 | std::mt19937_64 rng{1234567890UL + (uint64_t)getpid() + (uint64_t)this + |
| 37 | (uint64_t)pthread_self()}; |
| 38 | #else |
| 39 | LowDiscrepancy rng{1}; // 234567890UL + (uint64_t)getpid() + (uint64_t)this + |
| 40 | // (uint64_t)pthread_self()}; |
| 41 | #endif |
| 42 | #endif |
| 43 | |
| 44 | std::geometric_distribution<uint64_t> geom{SAMPLE_PROBABILITY}; |
| 45 | |
| 46 | public: |
| 47 | Sampler() { |
| 48 | #if !SAMPLER_DETERMINISTIC |
| 49 | while (true) { |
| 50 | _next = geom(rng); |
| 51 | if (_next != 0) { |
| 52 | break; |
| 53 | } |
| 54 | } |
| 55 | #else |
| 56 | _next = SAMPLE_RATE; |
| 57 | #endif |
| 58 | } |
| 59 | |
| 60 | inline ATTRIBUTE_ALWAYS_INLINE void unsample(uint64_t sz) { |
| 61 | if (_next < SAMPLE_RATE / 2) { |
| 62 | _next += sz; |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | inline ATTRIBUTE_ALWAYS_INLINE uint64_t sample(uint64_t sz) { |
| 67 | if (unlikely(_next <= sz)) { |
| 68 | // return updateSample(sz - _next); |
| 69 | return updateSample(sz); |
| 70 | } |
| 71 | assert(sz < _next); |
| 72 | _next -= sz; |
| 73 | return 0; |
| 74 | } |
| 75 | |
| 76 | uint64_t updateSample(uint64_t sz) { |
| 77 | #if SAMPLER_DETERMINISTIC |
| 78 | _next = SAMPLE_RATE; |
| 79 | #else |
| 80 | while (true) { |
| 81 | _next = geom(rng); |
| 82 | if (_next != 0) { |
| 83 | break; |
| 84 | } |
| 85 | } |
| 86 | #endif |
| 87 | if (sz >= SAMPLE_RATE) { |
| 88 | return sz; |
| 89 | } |
| 90 | return SAMPLE_RATE; |
| 91 | } |
| 92 | }; |