不是用流保存提振随机数发生器状态更快的替代方案 [英] Faster alternative than using streams to save boost random generator state

查看:181
本文介绍了不是用流保存提振随机数发生器状态更快的替代方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要能够保存/受此提振随机发生器的负荷状态:

I need to be able to save/load state of this boost random generator:

boost::variate_generator<boost::mt19937, boost::random::uniform_real_distribution<> > generator;

我做这种方式:

std::ostringstream content;
content << this->generator.engine();

问题是,这是令人难以置信的速度慢,是不是有来存储它的一些替代方法? (或接入本机格式随机生成的数据)。这code被封装在我们的 RandomGenerator 类,因此它可以有点讨厌。

The problem is, that this is incredibly slow, isn't there some alternative way to store it? (Or access the random generator data in native format). This code is encapsulated in our RandomGenerator class, so it can be little bit nasty.

推荐答案

一对夫妇的做法,无论是pretty哈克:

A couple of approaches, both pretty hacky:


  1. 只要抓住使用类似的原始字节:

  1. Just grab the raw bytes using something like:

typedef typename std::aligned_storage<sizeof(boost::mt19937)>::type mt19937_storage;
mt19937_storage storage;
std::memcpy(&storage, &generator, sizeof(generator));
//...
generator.engine() = *reinterpret_cast<boost::mt19937*>(storage);

这对于内存中保存和加载工作正常,但具体形式显然将编译器和体系结构相关的,所以如果你需要携带它的持久性将无法正常工作。对于格外小心点,你可以在 static_assert 抛出类似 is_trivially_copyable 来防范(不太可能)未来的变化来 mt19937

This works fine for in-memory saving and loading, but the exact format will obviously be compiler-and-architecture-dependent, so it won't work if you need portable persistence. For extra caution points, you could throw in a static_assert for something like is_trivially_copyable to guard against (unlikely) future changes to mt19937.

假设升压许可条款是可以接受的(他们可能是),让你自己Boost的 mersenne_twister 模板副本,并调整它接受一个指针状态阵列和数组索引的参考。那么国家是完全外部的引擎,你可以管理它,你喜欢的任何方式。

Assuming the terms of the Boost license are acceptable (they probably are), make your own copy of Boost's mersenne_twister template and tweak it to accept a pointer to the state array and a reference to the array index. Then the state is completely external to the engine, and you can manage it any way you like.

顺便说一句,如果这是一个很频繁的操作,你不需要MT19937的尤伯杯高维的均匀性,可以考虑使用<一个href=\"http://www.boost.org/doc/libs/1_53_0/doc/html/boost_random/reference.html#boost_random.reference.generators\"相对=nofollow>较小的国家的要求,如 taus88 不同的发动机。

Incidentally, if this is a very frequent operation and you don't need MT19937's uber-high-dimensional uniformity, you might consider using a different engine with smaller state requirements, such as taus88.

这篇关于不是用流保存提振随机数发生器状态更快的替代方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆