1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
#![feature(asm)]
extern crate time;
use std::default::Default;
use std::marker::PhantomData;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering::{Relaxed, SeqCst};
use std::sync::mpsc::{sync_channel, Receiver, SyncSender};
use std::sync::{Arc, Barrier, RwLock};
use std::thread::sleep;
use std::thread::{spawn, JoinHandle};
use std::time::Duration;
use time::precise_time_ns as time;
pub fn black_box<T>(dummy: T) -> T {
unsafe { asm!("" : : "r"(&dummy)) }
dummy
}
fn duration_to_ns(d: Duration) -> u64 {
d.as_secs() * 1_000_000_000 + d.subsec_nanos() as u64
}
enum Message<Global, Local> {
Exit,
Sync,
LocalInit(Box<'static + Fn(&mut Local) + Send>),
GlobalInit(Box<'static + Fn(&Global) + Send>),
BenchFor(Duration, Box<'static + Fn(&Global, &mut Local) + Send>),
DoneBench {
ops: u64,
time_spent: u64
},
}
pub struct BenchResult {
pub ops_per_sec: u64,
pub time_ns: u64,
}
pub struct TimedBench<Global, Local> {
global: Arc<RwLock<Global>>,
handles: Vec<JoinHandle<()>>,
senders: Vec<SyncSender<Message<Global, Local>>>,
receivers: Vec<Receiver<Message<Global, Local>>>,
barrier: Arc<Barrier>,
should_start: Arc<AtomicBool>,
should_stop: Arc<AtomicBool>,
_marker: PhantomData<Local>,
}
impl<Global, Local> TimedBench<Global, Local>
where Global: 'static + Default + Send + Sync,
Local: 'static + Default,
{
pub fn with_threads(num_threads: usize) -> Self {
let global = Arc::new(RwLock::new(Global::default()));
let mut senders = Vec::with_capacity(num_threads);
let mut receivers = Vec::with_capacity(num_threads);
let barrier = Arc::new(Barrier::new(num_threads + 1));
let should_start = Arc::new(AtomicBool::new(false));
let should_stop = Arc::new(AtomicBool::new(false));
let handles = (0..num_threads).map(|thread_id| {
let (our_send, their_recv) = sync_channel(1);
let (their_send, our_recv) = sync_channel(1);
senders.push(our_send);
receivers.push(our_recv);
let barrier = barrier.clone();
let global = global.clone();
let should_start = should_start.clone();
let should_stop = should_stop.clone();
spawn(move || {
let local = Local::default();
Self::thread_exec(thread_id,
local,
global,
their_send,
their_recv,
barrier,
should_start,
should_stop)
})
}).collect::<Vec<_>>();
TimedBench {
global: global,
handles,
senders,
receivers,
barrier,
should_start,
should_stop,
_marker: PhantomData,
}
}
fn thread_exec(_id: usize,
mut local: Local,
global: Arc<RwLock<Global>>,
send: SyncSender<Message<Global, Local>>,
recv: Receiver<Message<Global, Local>>,
barrier: Arc<Barrier>,
should_start: Arc<AtomicBool>,
should_stop: Arc<AtomicBool>)
{
while let Ok(msg) = recv.recv() {
match msg {
Message::DoneBench { .. } => unreachable!(),
Message::LocalInit(f) => {
f(&mut local);
}
Message::GlobalInit(f) => {
let global = global.read().expect(
"Worker failed to get a readlock for the global state for init."
);
f(&global);
}
Message::Sync => {
barrier.wait();
}
Message::BenchFor(duration, f) => {
let duration_ns = duration_to_ns(duration);
barrier.wait();
let global = global.read().expect(
"Worker failed to get a readlock for the global state."
);
while should_start.load(SeqCst) == false { }
let t0 = time();
let mut t1 = t0;
let mut ops = 0;
'outer: loop {
for _ in 0..50 {
if should_stop.load(Relaxed) {
break 'outer;
}
f(&global, &mut local);
ops += 1;
}
t1 = time();
if t1 - t0 > duration_ns {
should_stop.store(false, SeqCst);
break 'outer;
}
}
send.send(Message::DoneBench {
ops,
time_spent: t1 - t0,
}).expect("Worker failed to send DoneBench to the leader.");
}
Message::Exit => { break; }
}
}
}
pub fn with_local_state<F>(&self, f: F)
where F: 'static + Fn(&mut Local) + Send + Clone {
for send in &self.senders {
send.send(Message::LocalInit(Box::new(f.clone()))).unwrap();
}
}
pub fn with_global_state<F>(&self, f: F)
where F: 'static + Fn(&Global) + Send + Clone {
for send in &self.senders {
send.send(Message::GlobalInit(Box::new(f.clone()))).unwrap();
}
}
pub fn with_global_state_current_thread<F>(&self, f: F)
where F: Fn(&mut Global) {
f(&mut *self.global.write().unwrap());
}
pub fn sync(&self) {
for send in &self.senders {
send.send(Message::Sync).unwrap();
}
self.barrier.wait();
}
pub fn run_for(&self, duration: Duration, f: fn(&Global, &mut Local)) -> BenchResult {
self.sync();
for sender in &self.senders {
sender.send(Message::BenchFor(duration, Box::new(f.clone()))).unwrap();
}
self.should_start.store(false, SeqCst);
self.should_stop.store(false, SeqCst);
self.barrier.wait();
self.should_start.store(true, SeqCst);
let t0 = time();
sleep(duration);
let t1 = time();
let ns = duration_to_ns(duration);
assert!(t1 - t0 > ns, "We wanted to sleep {}ns, but slept only {}ns", ns, t1 - t0);
self.should_stop.store(false, SeqCst);
let ops = self.receivers.iter().map(|r| {
let msg = r.recv();
if let Ok(Message::DoneBench { ops, time_spent }) = msg {
let frac = time_spent as f64 / ns as f64;
if frac < 0.95 {
eprintln!("[WARN] Worker should run for {}ns, but only ran for {}ns",
ns, time_spent)
}
return ops;
} else {
panic!("Got back wrong message after `run_for`");
}
}).sum::<u64>() as f64;
let secs = ns as f64 / 1_000_000_000.0;
let ops_per_sec = ops / secs;
BenchResult {
ops_per_sec: ops_per_sec as u64,
time_ns: ns,
}
}
}
impl<Global, Local> Drop for TimedBench<Global, Local> {
fn drop(&mut self) {
for s in &self.senders {
s.send(Message::Exit).expect("Failed to send message to thread in TimedBench::Drop");
}
for h in self.handles.drain(..) {
h.join().expect("Failed to join thread handle in TimedBench::Drop");
}
}
}