std::mt19937
is a typedef of std::mersenne_twister_engine
. Should I be using my own template parameters for the latter if I'm switching between different floating point precisions in my sampling? If so, how?
Right now I have something like this
#include <random>
#include <iostream>
int main()
{
using float_type = double;
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<float_type> dis(1.0, 2.0);
for (int n = 0; n < 1e6; ++n) {
std::cout << dis(gen) << ' ';
}
std::cout << '\n';
}
but when I switch using float_type = double;
to using float_type = float;
there isn't much of a speedup. Actually, in some other code I have, using float
is actually much slower!
Here's a makefile if it helps. I used time ./prog
after I compile with make
as a rough timer, and I am running Ubuntu 18.04.2 LTS and my processor is a Intel® Xeon(R) CPU E3-1241 v3 @ 3.50GHz × 8 .
PROG = prog
SRCS = main.cpp
OBJS = main.o
CXX = g++
CXXFLAGS = -std=c++11 -O3 $(INCLUDES) -pg
all: $(PROG)
$(PROG): $(OBJS)
$(CXX) -o $@ $(OBJS)
main.cpp :
$(CXX) $(CXXFLAGS) -c
main.o : main.cpp
$(CXX) $(CXXFLAGS) -c main.cpp
.PHONY: clean
clean:
rm -f $(PROG) $(OBJS)
Should I be using my own template parameters for the latter if I'm switching between different floating point precisions in my sampling? If so, how?
Sure, you could use 64bit engine for sampling doubles (mantissa is 53bit long) and 32bit engine for sampling floats.
#define USE_DOUBLES
...
#ifdef USE_DOUBLES
using float_type = double;
using rng = std::mt19937_64;
#else
using float_type = float;
using rng = std::mt19937;
#endif
mt19937_64 is alias for MT with generated 64bits of randomness per call