Saturday 16 December 2017

C++ : The unrandom random number...

I've been working in some C++, with boost to be precise, the machine I'm working towards finally has a processor with SSE3 in it, and so I've been to revisit the GUID generation code, boost specifies a couple of defines you can set up before incluiding the uuids header to help...

#include <iostream>
#ifndef BOOST_UUID_USE_SSE3
#define BOOST_UUID_USE_SSE3
#endif
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/lexical_cast.hpp>

const std::string GetGuid();

int main ()
{
for (unsigned int i(0);
i < 100000;
++i)
{
std::cout << GetGuid() << "\r\n";
}
}


const std::string GetGuid()
{
boost::uuids::uuid l_guid =
boost::uuids::random_generator()();
return boost::lexical_cast<std::string>(l_guid);
}

This code looks fairly innocuous, "GetGuid" is the key part, you may argue that you're always setting the random number generator up, each and every call, but the output is fairly simple, this is only a test....




However, if we look carefully, there is always one column the same, when running on the screen this is very obvious...


Generating hundreds of thousands, taking minutes and minutes hasn't changed that one character.

Why this is isn't clear to me, I need to do some more digging.  I'm going to hazzard a guess it's that we construct and release the number generator each pass, we should perhaps instantiate one and keep it, so the sequence of randomness is preserved.

Any suggestions?  Hit the comments below!




P.S. Yes, I know I've not used RAII with the l_guid assignment there, but I'm in a hurry and only just noticed.

2 comments: