Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit c010cf4

Browse files
author
Ivan Baidakou
committed
Use <random> instead of C's rand()
1 parent 7e0b06c commit c010cf4

File tree

2 files changed

+23
-12
lines changed

2 files changed

+23
-12
lines changed

src/statsd_client.cpp

Lines changed: 22 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
#include <string.h>
55
#include <stdio.h>
66
#include <sys/types.h>
7+
#include <random>
78
#include "statsd_client.h"
89

910

@@ -30,17 +31,6 @@ inline bool fequal(float a, float b)
3031
return ( fabs(a - b) < epsilon );
3132
}
3233

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-
4434
struct _StatsdClientData {
4535
int sock;
4636
struct sockaddr_in server;
@@ -50,13 +40,33 @@ struct _StatsdClientData {
5040
short port;
5141
bool init;
5242

43+
std::default_random_engine rng_engine;
44+
std::uniform_real_distribution<> rng_dist;
45+
46+
5347
char errmsg[1024];
5448
};
5549

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+
5661
StatsdClient::StatsdClient(const string& host, int port, const string& ns)
5762
{
5863
d = new _StatsdClientData;
64+
5965
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+
6070
config(host, port, ns);
6171
srand(time(NULL));
6272
}
@@ -156,7 +166,7 @@ int StatsdClient::timing(const string& key, size_t ms, float sample_rate)
156166

157167
int StatsdClient::send(string key, size_t value, const string &type, float sample_rate)
158168
{
159-
if (!should_send(sample_rate)) {
169+
if (!should_send(this->d, sample_rate)) {
160170
return 0;
161171
}
162172

src/statsd_client.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
#include <string>
88

9+
910
namespace statsd {
1011

1112
struct _StatsdClientData;

0 commit comments

Comments
 (0)