In Python I have the following simple code:
N = 10000
mu = 0.0001
iterations = 10000
l = 10
@nb.njit()
def func1(N, l, mu, iterations):
intList = [0]*N
for x in range(iterations):
for number in range(N):
for position in range(l):
if random.random() < mu:
intList[number] = intList[number] ^ (1 << position)
func1(N, l, mu, iterations)
count = 1
print(timeit(lambda: func1(N, l, mu, iterations), number=count))
>>> 5.677
I'm not used to C++ but wanted to see, how quick it would be compared to the Python version. Since my Python code is quite simple I thought I could give it a try. My C++ code that should be equivalent to the Python code is
#include <iostream>
#include <random>
using namespace std;
int func1(int iterations, int l, int N, float mu)
{
std::random_device rd; //Will be used to obtain a seed for the random number engine
std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
std::uniform_real_distribution<> dis(0.0, 1.0);
std::vector<int> intList(N);
//for (int i = 0; i < N; i++)
// cout << intList[i];
//cout << "\n";
int x, number, position;
for (x = 0; x < iterations; x++) {
for (number = 0; number < N; number++) {
for (position = 0; position < l; position++) {
if (dis(gen) < mu) {
intList[number] = intList[number] ^ (1 << position);
}
}
}
}
//for (int i = 0; i < N; i++)
// cout << intList[i];
return 0;
}
int main()
{
int N, l, iterations;
float mu;
N = 10000;
mu = 0.0001;
iterations = 10000;
l = 10;
func1(iterations, l, N, mu);
cout << "\nFertig";
}
But this code takes up to 5-10 times longer. I'm really surprised by that. What is the explanation for that?