Why is my python 3 implementation much faster than the one I wrote in C++?

前端 未结 3 701
北荒
北荒 2021-01-27 09:45

I know that C++ should be much faster than Python 3 because it is a compiled language as opposed to an interpreted language.

I wrote 2 two programs that use the Monte

3条回答
  •  广开言路
    2021-01-27 10:20

    The main problem is that you're reseeding a random number generator for each random number in your C++ code. Additionally you're not compiling with optimizations enabled (-O3).

    I moved the initialization of the random number generator outside the randomFloat function (equally, you could use static variables inside the function):

    random_device rd;
    default_random_engine generator(rd()); // rd() provides a random seed
    uniform_real_distribution distribution(0,1);
    
    float randomFloat() {
        float x = distribution(generator);
        return x;
    }
    

    and compiled with -O3 and now C++ is considerably faster than Python


    Another possibility could be that python and C++ code use a different random number generator. Python random module (C code here) uses a MT19937 Mersenne Twister random number generator that is a fast PRNG optimized specifically for numerical problems such as Monte Carlo; the algorithm of default_random_engine in C++ is implementation-defined. As pointed out by Melak47, you can force the use of MT19937 PRNG in C++ with:

    mt19937 generator(rd());
    

    or

    mt19937_64 generator(rd());
    

    P.S., Python outperforming C++ is not unheard of; the C++ algorithms value genericity whereas the Python algorithms are often quite optimized for some use cases. See for example this question on substring matching.

提交回复
热议问题