4
4
#include < string.h>
5
5
#include < stdio.h>
6
6
#include < sys/types.h>
7
+ #include < random>
7
8
#include " statsd_client.h"
8
9
9
10
@@ -30,17 +31,6 @@ inline bool fequal(float a, float b)
30
31
return ( fabs (a - b) < epsilon );
31
32
}
32
33
33
- inline bool should_send (float sample_rate)
34
- {
35
- if ( fequal (sample_rate, 1.0 ) )
36
- {
37
- return true ;
38
- }
39
-
40
- float p = ((float )rand () / RAND_MAX);
41
- return sample_rate > p;
42
- }
43
-
44
34
struct _StatsdClientData {
45
35
int sock;
46
36
struct sockaddr_in server;
@@ -50,13 +40,33 @@ struct _StatsdClientData {
50
40
short port;
51
41
bool init;
52
42
43
+ std::default_random_engine rng_engine;
44
+ std::uniform_real_distribution<> rng_dist;
45
+
46
+
53
47
char errmsg[1024 ];
54
48
};
55
49
50
+ inline bool should_send (_StatsdClientData* d, float sample_rate)
51
+ {
52
+ if ( fequal (sample_rate, 1.0 ) )
53
+ {
54
+ return true ;
55
+ }
56
+
57
+ float p = d->rng_dist (d->rng_engine );
58
+ return sample_rate > p;
59
+ }
60
+
56
61
StatsdClient::StatsdClient (const string& host, int port, const string& ns)
57
62
{
58
63
d = new _StatsdClientData;
64
+
59
65
d->sock = -1 ;
66
+ std::random_device rd;
67
+ d->rng_engine = std::default_random_engine (rd () );
68
+ d->rng_dist = std::uniform_real_distribution<>(0 .0f , 1 .0f );
69
+
60
70
config (host, port, ns);
61
71
srand (time (NULL ));
62
72
}
@@ -156,7 +166,7 @@ int StatsdClient::timing(const string& key, size_t ms, float sample_rate)
156
166
157
167
int StatsdClient::send (string key, size_t value, const string &type, float sample_rate)
158
168
{
159
- if (!should_send (sample_rate)) {
169
+ if (!should_send (this -> d , sample_rate)) {
160
170
return 0 ;
161
171
}
162
172
0 commit comments