performance measurements

Each table row shows performance measurements for this Rust program with a particular command-line input value N.

 N  CPU secs Elapsed secs Memory KB Code B ≈ CPU Load
250,0000.440.246922097  42% 60% 57% 43%
2,500,0003.211.6141,4402097  31% 66% 89% 28%
25,000,00025.609.60154,6322097  84% 44% 83% 58%

Read the ↓ make, command line, and program output logs to see how this program was run.

Read k-nucleotide benchmark to see what this program should do.

 notes

rustc 1.0.0-alpha (44a287e6e 2015-01-08 17:03:40 -0800)

 k-nucleotide Rust program source code

// The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// contributed by TeXitoi

#![feature(box_syntax)]

use std::ascii::OwnedAsciiExt;
use std::slice;
use std::sync::Arc;
use std::thread::Thread;

static TABLE: [u8;4] = [ 'A' as u8, 'C' as u8, 'G' as u8, 'T' as u8 ];
static TABLE_SIZE: usize = 2 << 16;

static OCCURRENCES: [&'static str;5] = [
    "GGT",
    "GGTA",
    "GGTATT",
    "GGTATTTTAATT",
    "GGTATTTTAATTTATAGT",
];

// Code implementation

#[derive(PartialEq, PartialOrd, Ord, Eq)]
struct Code(u64);

impl Copy for Code {}

impl Code {
    fn hash(&self) -> u64 {
        let Code(ret) = *self;
        return ret;
    }

    fn push_char(&self, c: u8) -> Code {
        Code((self.hash() << 2) + (pack_symbol(c) as u64))
    }

    fn rotate(&self, c: u8, frame: usize) -> Code {
        Code(self.push_char(c).hash() & ((1u64 << (2 * frame)) - 1))
    }

    fn pack(string: &str) -> Code {
        string.bytes().fold(Code(0u64), |a, b| a.push_char(b))
    }

    fn unpack(&self, frame: usize) -> String {
        let mut key = self.hash();
        let mut result = Vec::new();
        for _ in (0..frame) {
            result.push(unpack_symbol((key as u8) & 3));
            key >>= 2;
        }

        result.reverse();
        String::from_utf8(result).unwrap()
    }
}

// Hash table implementation

trait TableCallback {
    fn f(&self, entry: &mut Entry);
}

struct BumpCallback;

impl TableCallback for BumpCallback {
    fn f(&self, entry: &mut Entry) {
        entry.count += 1;
    }
}

struct PrintCallback(&'static str);

impl TableCallback for PrintCallback {
    fn f(&self, entry: &mut Entry) {
        let PrintCallback(s) = *self;
        println!("{}\t{}", entry.count, s);
    }
}

struct Entry {
    code: Code,
    count: usize,
    next: Option<Box<Entry>>,
}

struct Table {
    items: Vec<Option<Box<Entry>>>
}

struct Items<'a> {
    cur: Option<&'a Entry>,
    items: slice::Iter<'a, Option<Box<Entry>>>,
}

impl Table {
    fn new() -> Table {
        Table {
            items: (0..TABLE_SIZE).map(|_| None).collect()
        }
    }

    fn search_remainder<C:TableCallback>(item: &mut Entry, key: Code, c: C) {
        match item.next {
            None => {
                let mut entry = box Entry {
                    code: key,
                    count: 0,
                    next: None,
                };
                c.f(&mut *entry);
                item.next = Some(entry);
            }
            Some(ref mut entry) => {
                if entry.code == key {
                    c.f(&mut **entry);
                    return;
                }

                Table::search_remainder(&mut **entry, key, c)
            }
        }
    }

    fn lookup<C:TableCallback>(&mut self, key: Code, c: C) {
        let index = key.hash() % (TABLE_SIZE as u64);

        {
            if self.items[index as usize].is_none() {
                let mut entry = box Entry {
                    code: key,
                    count: 0,
                    next: None,
                };
                c.f(&mut *entry);
                self.items[index as usize] = Some(entry);
                return;
            }
        }

        {
            let entry = self.items[index as usize].as_mut().unwrap();
            if entry.code == key {
                c.f(&mut **entry);
                return;
            }

            Table::search_remainder(&mut **entry, key, c)
        }
    }

    fn iter(&self) -> Items {
        Items { cur: None, items: self.items.iter() }
    }
}

impl<'a> Iterator for Items<'a> {
    type Item = &'a Entry;

    fn next(&mut self) -> Option<&'a Entry> {
        let ret = match self.cur {
            None => {
                let i;
                loop {
                    match self.items.next() {
                        None => return None,
                        Some(&None) => {}
                        Some(&Some(ref a)) => { i = &**a; break }
                    }
                }
                self.cur = Some(&*i);
                &*i
            }
            Some(c) => c
        };
        match ret.next {
            None => { self.cur = None; }
            Some(ref next) => { self.cur = Some(&**next); }
        }
        return Some(ret);
    }
}

// Main program

fn pack_symbol(c: u8) -> u8 {
    match c as char {
        'A' => 0,
        'C' => 1,
        'G' => 2,
        'T' => 3,
        _ => panic!("{}", c as char),
    }
}

fn unpack_symbol(c: u8) -> u8 {
    TABLE[c as usize]
}

fn generate_frequencies(mut input: &[u8], frame: usize) -> Table {
    let mut frequencies = Table::new();
    if input.len() < frame { return frequencies; }
    let mut code = Code(0);

    // Pull first frame.
    for _ in (0..frame) {
        code = code.push_char(input[0]);
        input = &input[1..];
    }
    frequencies.lookup(code, BumpCallback);

    while input.len() != 0 && input[0] != ('>' as u8) {
        code = code.rotate(input[0], frame);
        frequencies.lookup(code, BumpCallback);
        input = &input[1..];
    }
    frequencies
}

fn print_frequencies(frequencies: &Table, frame: usize) {
    let mut vector = Vec::new();
    for entry in frequencies.iter() {
        vector.push((entry.count, entry.code));
    }
    vector.as_mut_slice().sort();

    let mut total_count = 0;
    for &(count, _) in vector.iter() {
        total_count += count;
    }

    for &(count, key) in vector.iter().rev() {
        println!("{} {:.3}",
                 key.unpack(frame).as_slice(),
                 (count as f32 * 100.0) / (total_count as f32));
    }
    println!("");
}

fn print_occurrences(frequencies: &mut Table, occurrence: &'static str) {
    frequencies.lookup(Code::pack(occurrence), PrintCallback(occurrence))
}

fn get_sequence<R: Buffer>(r: &mut R, key: &str) -> Vec<u8> {
    let mut res = Vec::new();
    for l in r.lines().map(|l| l.ok().unwrap())
        .skip_while(|l| key != &l[..key.len()]).skip(1)
    {
        res.push_all(l.trim().as_bytes());
    }
    res.into_ascii_uppercase()
}

fn main() {
    let input = get_sequence(&mut *std::io::stdin().lock(), ">THREE");
    let input = Arc::new(input);

    let nb_freqs: Vec<_> = (1..3).map(|i| {
        let input = input.clone();
        (i, Thread::scoped(move|| generate_frequencies(&**input, i)))
    }).collect();
    let occ_freqs: Vec<_> = OCCURRENCES.iter().map(|&occ| {
        let input = input.clone();
        Thread::scoped(move|| generate_frequencies(&**input, occ.len()))
    }).collect();

    for (i, freq) in nb_freqs.into_iter() {
        print_frequencies(&freq.join().ok().unwrap(), i);
    }
    for (&occ, freq) in OCCURRENCES.iter().zip(occ_freqs.into_iter()) {
        print_occurrences(&mut freq.join().ok().unwrap(), occ);
    }
}

 make, command-line, and program output logs

Sat, 10 Jan 2015 20:21:43 GMT

MAKE:
/usr/local/src/rust/bin/rustc -C opt-level=3 -C target-cpu=core2 -C lto knucleotide.rs -o knucleotide.rust_run
knucleotide.rs:251:16: 251:23 warning: use of unstable item
knucleotide.rs:251     for l in r.lines().map(|l| l.ok().unwrap())
                                  ^~~~~~~
note: this feature may not be used in the beta release channel
knucleotide.rs:254:13: 254:42 warning: use of unstable item: likely to be replaced by a more optimized extend
knucleotide.rs:254         res.push_all(l.trim().as_bytes());
                               ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
note: this feature may not be used in the beta release channel
knucleotide.rs:256:9: 256:31 warning: use of unstable item: would prefer to do this in a more general way
knucleotide.rs:256     res.into_ascii_uppercase()
                           ^~~~~~~~~~~~~~~~~~~~~~
note: this feature may not be used in the beta release channel
knucleotide.rs:260:53: 260:59 warning: use of unstable item
knucleotide.rs:260     let input = get_sequence(&mut *std::io::stdin().lock(), ">THREE");
                                                                       ^~~~~~
note: this feature may not be used in the beta release channel
knucleotide.rs:260:36: 260:50 warning: use of unstable item
knucleotide.rs:260     let input = get_sequence(&mut *std::io::stdin().lock(), ">THREE");
                                                      ^~~~~~~~~~~~~~
note: this feature may not be used in the beta release channel
knucleotide.rs:265:13: 265:27 warning: use of unstable item: may change with specifics of new Send semantics
knucleotide.rs:265         (i, Thread::scoped(move|| generate_frequencies(&**input, i)))
                               ^~~~~~~~~~~~~~
note: this feature may not be used in the beta release channel
knucleotide.rs:269:9: 269:23 warning: use of unstable item: may change with specifics of new Send semantics
knucleotide.rs:269         Thread::scoped(move|| generate_frequencies(&**input, occ.len()))
                           ^~~~~~~~~~~~~~
note: this feature may not be used in the beta release channel
knucleotide.rs:7:1: 7:24 warning: unstable feature
knucleotide.rs:7 #![feature(box_syntax)]
                 ^~~~~~~~~~~~~~~~~~~~~~~
note: this feature may not be used in the beta release channel
rm knucleotide.rs
10.03s to complete and log all make actions

COMMAND LINE:
./knucleotide.rust_run 0 < knucleotide-input25000000.txt

PROGRAM OUTPUT:
A 30.295
T 30.151
C 19.800
G 19.754

AA 9.177
TA 9.132
AT 9.131
TT 9.091
CA 6.002
AC 6.001
AG 5.987
GA 5.984
CT 5.971
TC 5.971
GT 5.957
TG 5.956
CC 3.917
GC 3.911
CG 3.909
GG 3.902

1471758	GGT
446535	GGTA
47336	GGTATT
893	GGTATTTTAATT
893	GGTATTTTAATTTATAGT

Revised BSD license

  Home   Conclusions   License   Play