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

后端 未结 6 1664
日久生厌
日久生厌 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 22:04

    The answer is simply that Python deals with objects for everything and that it doesn't have JIT by default. So rather than being very efficient by modifying a few bytes on the stack and optimizing the hot parts of the code (i.e., the iteration) – Python chugs along with rich objects representing numbers and no on-the-fly optimizations.

    If you tried this in a variant of Python that has JIT (for example, PyPy) I guarantee you that you'll see a massive difference.

    A general tip is to avoid standard Python for very computationally expensive operations (especially if this is for a backend serving requests from multiple clients). Java, C#, JavaScript, etc. with JIT are incomparably more efficient.

    By the way, if you want to write your example in a more Pythonic manner, you could do it like this:

    from datetime import datetime
    start_time = datetime.now()
    
    max_number = 20
    x = max_number
    while True:
        i = 2
        while i <= max_number:
            if x % i: break
            i += 1
        else:
            # x was not divisible by 2...20
            break
        x += 1
    
    print('number:       %d' % x)
    print('time elapsed: %d seconds' % (datetime.now() - start_time).seconds)
    

    The above executed in 90 seconds for me. The reason it's faster relies on seemingly stupid things like x being shorter than start, that I'm not assigning variables as often, and that I'm relying on Python's own control structures rather than variable checking to jump in/out of loops.

提交回复
热议问题