Why is my computation so much faster in C# than Python

后端 未结 6 1660
日久生厌
日久生厌 2020-12-07 21:40

Below is a simple piece of process coded in C# and Python respectively (for those of you curious about the process, it\'s the solution for Problem

6条回答
  •  孤城傲影
    2020-12-07 21:57

    Try python JIT Implementations like pypy and numba or cython if you want fast as C but sacrifice a bit of code readability.

    e.g in pypy

    # PyPy
    
    number 232792560
    
    time elapsed = 4.000000 sec.
    

    e.g in cython

    # Cython
    
    number 232792560
    
    time elapsed = 1.000000 sec.
    

    Cython Source:

    from datetime import datetime
    
    cpdef void run():
        t0 = datetime.now()
        cdef int max_number = 20
        found = False
        cdef int start = max_number
        cdef int i
        while not found:
            found = True
            i = 2
            while ((i < max_number + 1) and found):
                if (start % i) != 0:
                    found = False
                i += 1
            start += 1
    
        print("number {0:d}\n".format(start - 1))
    
        print("time elapsed = {0:f} sec.\n".format((datetime.now() - t0).seconds))
    

提交回复
热议问题