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

前端 未结 3 704
北荒
北荒 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条回答
  •  猫巷女王i
    2021-01-27 10:23

    Not meant as an answer to your question why python is faster, just to show that python can get event faster and neater for this problem.

    To possibilities to speed things up in python:

    Use numpy vectorization:

    import numpy as np
    
    def pi(N):
        x, y = np.random.uniform(-1, 1, size=(2, N))
        in_circle = np.count_nonzero(x**2 + y**2 <= 1)
        return 4 * in_circle / N
    

    And / or numba just in time compilation:

    from numba import jit
    import random
    
    @jit
    def pi(N):
        in_circle = 0
        for i in range(N):
            x = 2 * random.random() - 1
            y = 2 * random.random() - 1
    
            if x**2 + y**2 <= 1:
                in_circle += 1
         return 4 * in_circle / N
    

提交回复
热议问题