1 // The Computer Language Benchmarks Game
2 // http://benchmarksgame.alioth.debian.org/
4 // contributed by the Rust Project Developers
6 // Copyright (c) 2013-2014 The Rust Project Developers
8 // All rights reserved.
10 // Redistribution and use in source and binary forms, with or without
11 // modification, are permitted provided that the following conditions
14 // - Redistributions of source code must retain the above copyright
15 // notice, this list of conditions and the following disclaimer.
17 // - Redistributions in binary form must reproduce the above copyright
18 // notice, this list of conditions and the following disclaimer in
19 // the documentation and/or other materials provided with the
22 // - Neither the name of "The Computer Language Benchmarks Game" nor
23 // the name of "The Computer Language Shootout Benchmarks" nor the
24 // names of its contributors may be used to endorse or promote
25 // products derived from this software without specific prior
26 // written permission.
28 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
29 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
31 // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
32 // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
33 // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
34 // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
35 // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
36 // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
37 // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
38 // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
39 // OF THE POSSIBILITY OF SUCH DAMAGE.
42 use std::io::{self, Write};
43 use std::sync::{Arc, Mutex};
47 const LINE_LEN: usize = 60;
49 const BLOCK_LINES: usize = 512;
50 const BLOCK_THOROUGHPUT: usize = LINE_LEN * BLOCK_LINES;
51 const BLOCK_LEN: usize = BLOCK_THOROUGHPUT + BLOCK_LINES;
53 const STDIN_BUF: usize = (LINE_LEN + 1) * 1024;
54 const LOOKUP_SIZE: usize = 4 * 1024;
55 const LOOKUP_SCALE: f32 = (LOOKUP_SIZE - 1) as f32;
57 const ALU: &'static [u8] =
58 b"GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGG\
59 GAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGA\
60 CCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAAT\
61 ACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCA\
62 GCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGG\
63 AGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCC\
64 AGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAA";
66 const IUB: &'static [(u8, f32)] =
67 &[(b'a', 0.27), (b'c', 0.12), (b'g', 0.12),
68 (b't', 0.27), (b'B', 0.02), (b'D', 0.02),
69 (b'H', 0.02), (b'K', 0.02), (b'M', 0.02),
70 (b'N', 0.02), (b'R', 0.02), (b'S', 0.02),
71 (b'V', 0.02), (b'W', 0.02), (b'Y', 0.02)];
73 const HOMOSAPIENS: &'static [(u8, f32)] =
74 &[(b'a', 0.3029549426680),
75 (b'c', 0.1979883004921),
76 (b'g', 0.1975473066391),
77 (b't', 0.3015094502008)];
79 // We need a specific Rng,
80 // so implement this manually
82 const MODULUS: u32 = 139968;
83 const MULTIPLIER: u32 = 3877;
84 const ADDITIVE: u32 = 29573;
86 // Why doesn't rust already have this?
87 // Algorithm directly taken from Wikipedia
88 fn powmod(mut base: u64, mut exponent: u32, modulus: u64) -> u64 {
93 if exponent & 1 == 1 {
105 // Just a typical LCRNG
111 pub fn new() -> Rng {
115 pub fn max_value() -> u32 {
119 pub fn normalize(p: f32) -> u32 {
120 (p * MODULUS as f32).floor() as u32
123 pub fn gen(&mut self) -> u32 {
124 self.last = (self.last * MULTIPLIER + ADDITIVE) % MODULUS;
128 // This allows us to fast-forward the RNG,
129 // allowing us to run it in parallel.
130 pub fn future(&self, n: u32) -> Rng {
131 let a = MULTIPLIER as u64;
132 let b = ADDITIVE as u64;
133 let m = MODULUS as u64;
135 // (a^n - 1) mod (a-1) m
136 // x_k = ((a^n x_0 mod m) + --------------------- b) mod m
139 // Since (a - 1) divides (a^n - 1) mod (a-1) m,
140 // the subtraction does not overflow and thus can be non-modular.
143 (powmod(a, n, m) * self.last as u64) % m +
144 (powmod(a, n, (a-1) * m) - 1) / (a-1) * b;
146 Rng { last: (new_seed % m) as u32 }
151 // This will end up keeping track of threads, like
152 // in the other multithreaded Rust version, in
153 // order to keep writes in order.
155 // This is stolen from another multithreaded Rust
156 // implementation, although that implementation
157 // was not able to parallelize the RNG itself.
158 struct BlockSubmitter<W: io::Write> {
160 pub waiting_on: usize,
163 impl<W: io::Write> BlockSubmitter<W> {
164 fn submit(&mut self, data: &[u8], block_num: usize) -> Option<io::Result<()>> {
165 if block_num == self.waiting_on {
166 self.waiting_on += 1;
167 Some(self.submit_async(data))
174 fn submit_async(&mut self, data: &[u8]) -> io::Result<()> {
175 self.writer.write_all(data)
180 // For repeating strings as output
181 fn fasta_static<W: io::Write>(
188 // The aim here is to print a short(ish) string cyclically
189 // with line breaks as appropriate.
191 // The secret technique is to repeat the string such that
192 // any wanted line is a single offset in the string.
194 // This technique is stolen from the Haskell version.
196 try!(writer.write_all(header));
198 // Maximum offset is data.len(),
199 // Maximum read len is LINE_LEN
200 let stream = data.iter().cloned().cycle();
201 let mut extended: Vec<u8> = stream.take(data.len() + LINE_LEN + 1).collect();
205 let write_len = min(LINE_LEN, n);
206 let end = offset + write_len;
209 let tmp = extended[end];
210 extended[end] = b'\n';
211 try!(writer.write_all(&extended[offset..end + 1]));
215 offset %= data.len();
222 // For RNG streams as output
223 fn fasta<W: io::Write + Send + 'static>(
224 submitter: &Arc<Mutex<BlockSubmitter<W>>>,
226 table: &'static [(u8, f32)],
231 // Here the lookup table is part of the algorithm and needs the
232 // original probabilities (scaled with the LOOKUP_SCALE), because
234 fn sum_and_scale(a: &'static [(u8, f32)]) -> Vec<(u8, f32)> {
236 let mut result: Vec<(u8, f32)> = a.iter().map(|e| {
238 (e.0, p * LOOKUP_SCALE)
240 let result_len = result.len();
241 result[result_len - 1].1 = LOOKUP_SCALE;
245 fn make_lookup(a: &[(u8, f32)]) -> [(u8, f32); LOOKUP_SIZE] {
246 let mut lookup = [(0, 0f32); LOOKUP_SIZE];
248 for (i, slot) in lookup.iter_mut().enumerate() {
249 while a[j].1 < (i as f32) {
258 try!(submitter.lock().unwrap().submit_async(header));
261 let lookup_table = Arc::new(make_lookup(&sum_and_scale(table)));
263 let thread_count = 4;
264 let mut threads = Vec::new();
265 for block_num in (0..thread_count) {
266 let offset = BLOCK_THOROUGHPUT * block_num;
268 let local_submitter = submitter.clone();
269 let local_lookup_table = lookup_table.clone();
270 let local_rng = rng.future(offset as u32);
272 threads.push(thread::spawn(move || {
277 n.saturating_sub(offset),
284 for thread in threads {
285 try!(thread.join().unwrap());
288 *rng = rng.future(n as u32);
293 // A very optimized writer.
294 // I have a feeling a simpler version wouldn't slow
295 // things down too much, though, since the RNG
296 // is the really heavy hitter.
297 fn gen_block<W: io::Write>(
298 submitter: Arc<Mutex<BlockSubmitter<W>>>,
299 lookup_table: Arc<[(u8, f32)]>,
302 mut block_num: usize,
306 // Include newlines in block
307 length += length / LINE_LEN;
308 let block: &mut [u8] = &mut [b'\n'; BLOCK_LEN];
312 let gen_into = &mut block[..min(length, BLOCK_LEN)];
314 // Write random numbers, skipping newlines
315 for (i, byte) in gen_into.iter_mut().enumerate() {
316 if (i + 1) % (LINE_LEN + 1) != 0 {
317 let p = rng.gen() as f32 * (LOOKUP_SCALE / MODULUS as f32);
318 *byte = lookup_table[p as usize..LOOKUP_SIZE].iter().find(
319 |le| le.1 >= p).unwrap().0;
325 if length >= BLOCK_LEN { &mut *block }
326 else if length % (LINE_LEN + 1) == 0 { &mut block[..length] }
327 else { &mut block[..length + 1] }
330 *write_out.last_mut().unwrap() = b'\n';
332 // Make sure to release lock before calling `yield_now`
333 let res = { submitter.lock().unwrap().submit(write_out, block_num) };
336 Some(result) => { try!(result); break; }
337 None => std::thread::yield_now()
340 block_num += block_stride;
341 rng = rng.future((BLOCK_THOROUGHPUT * (block_stride - 1)) as u32);
342 length = length.saturating_sub(BLOCK_LEN * (block_stride - 1));
344 length = length.saturating_sub(BLOCK_LEN);
350 fn run<W: io::Write + Send + 'static>(writer: W) -> io::Result<()> {
351 let n = std::env::args_os().nth(1)
352 .and_then(|s| s.into_string().ok())
353 .and_then(|n| n.parse().ok())
356 let rng = &mut Rng::new();
358 // Use automatic buffering for the static version...
359 let mut writer = io::BufWriter::with_capacity(STDIN_BUF, writer);
360 try!(fasta_static(&mut writer, b">ONE Homo sapiens alu\n", ALU, n * 2));
362 // ...but the dynamic version does its own buffering already
363 let writer = try!(writer.into_inner());
364 let submitter = Arc::new(Mutex::new(BlockSubmitter { writer: writer, waiting_on: 0 }));
366 { submitter.lock().unwrap().waiting_on = 0; }
367 try!(fasta(&submitter, b">TWO IUB ambiguity codes\n", &IUB, rng, n * 3));
368 { submitter.lock().unwrap().waiting_on = 0; }
369 try!(fasta(&submitter, b">THREE Homo sapiens frequency\n", &HOMOSAPIENS, rng, n * 5));
375 run(io::stdout()).unwrap()