Python is a much more dynamic language than C or C #. The main reason the loop is so slow is that on each pass the CPython interpreter does an extra job that takes time: in particular, it connects the name x to the next object from the iterator, and then when it evaluates it needs to find it again name x .
As @Sven Marnach noted, you can call the function of the numpy.fill() method, and that is fast. This function is compiled by C, or perhaps Fortran, and it will simply numpy.array over the addresses of the numpy.array data numpy.array and fill in the values. Much less dynamic than Python, which is good for this simple case.
But now consider PyPy. After starting your program under PyPy, the JIT analyzes what your code actually does. In this example, he notes that the name x not used for anything other than the destination, and can optimize the name binding. This example should be what PyPy greatly speeds up; PyPy will probably be ten times faster than regular Python (so only one tenth faster than C, not 1/100 faster).
http://pypy.org
As I understand it, PyPy will not work with Numpy yet, so you cannot just run existing Numpy code under PyPy. But the day is coming.
I am very happy PyPy. He offers the hope that we can write at a very high level of the language (Python), but at the same time we get almost the performance of writing things in the "assembler language" (C). For examples like this, Numpy can even surpass the performance of naive C code by using SIMD instructions from the CPU (SSE2, NEON, or something else). In this SIMD example, you can set four integers to 123 with each cycle, and it will be faster than a simple C cycle. (Unless the C compiler has used SIMD optimization! Which, think about it, most likely for this case. Therefore, we will return to βalmost C speed,β rather than faster for this example, but we can imagine more complex cases where the C compiler is not smart enough to optimize where the future PyPy might be.)
But do not pay attention to PyPy. If you will be working with Numpy, it is recommended that you examine all the functions, such as numpy.fill() , that speed up your code.