| 1 | /* boost nondet_random_speed.cpp performance test |
|---|
| 2 | * |
|---|
| 3 | * Copyright Jens Maurer 2000 |
|---|
| 4 | * Distributed under the Boost Software License, Version 1.0. (See |
|---|
| 5 | * accompanying file LICENSE_1_0.txt or copy at |
|---|
| 6 | * http://www.boost.org/LICENSE_1_0.txt) |
|---|
| 7 | * |
|---|
| 8 | * $Id: nondet_random_speed.cpp,v 1.5 2004/07/27 03:43:34 dgregor Exp $ |
|---|
| 9 | * |
|---|
| 10 | */ |
|---|
| 11 | |
|---|
| 12 | #include <iostream> |
|---|
| 13 | #include <string> |
|---|
| 14 | #include <boost/timer.hpp> |
|---|
| 15 | #include <boost/nondet_random.hpp> |
|---|
| 16 | |
|---|
| 17 | // set to your CPU frequency in MHz |
|---|
| 18 | static const double cpu_frequency = 200 * 1e6; |
|---|
| 19 | |
|---|
| 20 | static void show_elapsed(double end, int iter, const std::string & name) |
|---|
| 21 | { |
|---|
| 22 | double usec = end/iter*1e6; |
|---|
| 23 | double cycles = usec * cpu_frequency/1e6; |
|---|
| 24 | std::cout << name << ": " |
|---|
| 25 | << usec*1e3 << " nsec/loop = " |
|---|
| 26 | << cycles << " CPU cycles" |
|---|
| 27 | << std::endl; |
|---|
| 28 | } |
|---|
| 29 | |
|---|
| 30 | template<class Result, class RNG> |
|---|
| 31 | static void timing(RNG & rng, int iter, const std::string& name) |
|---|
| 32 | { |
|---|
| 33 | volatile Result tmp; // make sure we're not optimizing too much |
|---|
| 34 | boost::timer t; |
|---|
| 35 | for(int i = 0; i < iter; i++) |
|---|
| 36 | tmp = rng(); |
|---|
| 37 | show_elapsed(t.elapsed(), iter, name); |
|---|
| 38 | } |
|---|
| 39 | |
|---|
| 40 | template<class RNG> |
|---|
| 41 | void run(int iter, const std::string & name) |
|---|
| 42 | { |
|---|
| 43 | RNG rng; |
|---|
| 44 | timing<long>(rng, iter, name); |
|---|
| 45 | } |
|---|
| 46 | |
|---|
| 47 | int main(int argc, char*argv[]) |
|---|
| 48 | { |
|---|
| 49 | if(argc != 2) { |
|---|
| 50 | std::cerr << "usage: " << argv[0] << " iterations" << std::endl; |
|---|
| 51 | return 1; |
|---|
| 52 | } |
|---|
| 53 | |
|---|
| 54 | int iter = std::atoi(argv[1]); |
|---|
| 55 | |
|---|
| 56 | #ifdef __linux__ |
|---|
| 57 | boost::random_device dev; |
|---|
| 58 | timing<unsigned int>(dev, iter, "random_device"); |
|---|
| 59 | #else |
|---|
| 60 | #error The non-deterministic random device is currently available on Linux only. |
|---|
| 61 | #endif |
|---|
| 62 | |
|---|
| 63 | return 0; |
|---|
| 64 | } |
|---|