a loop for python interface #200
Replies: 4 comments
-
It sure looks right. Let me speculate on what might be happening here. In the given code, where we increment the same integer variable a hundred million times, the ideal scenario would be that the CPU loads the variable from memory into a register and performs an addl instruction. Once the data is in the register, the cost of adding to it becomes negligible. However, in the case of Python, which is an interpreted language, the code doesn't execute as described above. In Python, the interpreter handles the execution of the code. When the interpreter encounters the increment operation, it needs to load the value of x from memory into the stack by dereferencing a pointer, and then increment it. This process of indirection and stack manipulation can be slower compared to the efficient register operations in compiled code. Regarding Mojo, I don't know how it compiles Python code. But it looks like it is doing a great job. PS: To see a comparison of the relative slowness of different operations, see the below chart, A simple register op is the fastest thing we can do. |
Beta Was this translation helpful? Give feedback.
-
You can go even faster if you use built in from Time import now
def call():
x=0
for i in range(100000000):
x+=i
return x
let start_time=now()
let res1 = call()
let end_time=now()
print(end_time - start_time) # 2.122e-6 |
Beta Was this translation helpful? Give feedback.
-
Since you're not doing any IO in the loop the compiler can completely get rid of the loop and compute (n+1)*n/2 instead. In fact since you're using a constant number of iterations it can just compute the final value at compile time instead. You're really just measuring the overhead of printing and timing in Mojo. You probably want a better benchmark than this. |
Beta Was this translation helpful? Give feedback.
-
Agreed, mojo is probably compiling this loop to closed form arithmetic. |
Beta Was this translation helpful? Give feedback.
-
%%python
import time
def cal1():
x=0
for i in range(100000000):
x+=i
return x
start_time1=time.time()
res1 = cal1()
end_time1=time.time()
print('spend:',end_time1-start_time1)
print(res1)
I got python calculate result:
spend: 3.779045343399048
4999999950000000
for mojo, I use
from PythonInterface import Python
#let time = Python.import_module("time")
def cal2():
x= 0
for i in range(100000000):
x+=i
return x
let start_time2=time.time()
let res2 = cal2()
let end_time2=time.time()
print('spend:',end_time2-start_time2)
print(res2)
I got mojo result:
spend: 3.337860107421875e-06
4999999950000000
Did I write it right? Is mojo really that fast?
hope for your reply
Beta Was this translation helpful? Give feedback.
All reactions