Seems to work fines until I tried to increase the loop. For some unknown reason the core 1 stop.
This is the result if the loop is 1000.
But if you try a loop of 3000 it hangs. but only on core1.>>> %Run -c $EDITOR_CONTENT
PI calculation
One core cpu :
3.141593
time 0.061 seconds to calculate Pi using a loop of 1000.
Two cores cpu:
3.141593
time 0.041 seconds to calculate Pi using a loop of 1000.
>>>
This is the source code. It is just a split method to calculate PI on a loop.
Code: Select all
import utime
import _thread
MaxCount=1000
threadDone = False
threadResult = 0.0
def showTimeLapse(start,MaxCount):
lapse= (utime.ticks_ms() - start) / 1000.0
print(" time {:.3f} seconds".format(lapse),end="")
print(" to calculate Pi",end="")
print(" using a loop of {}.".format(MaxCount))
def PiCalcThread(Start, End, theLock):
global threadResult
global threadDone
r = PiCalc(Start,End)
#lock to transfer data
with theLock:
threadDone = True
threadResult = r
# using the Nilakantha series.
def PiCalc(Start,End):
r = 0.0
d1 = Start * 2.0
d2 = Start * 2.0 + 1.0
d3 = Start * 2.0 + 2.0
for i in range(Start,End):
d1 = d1 + 2.0
d2 = d2 + 2.0
d3 = d3 + 2.0
if (i & 1) == 0:
r = r + ( 4.0 / ( d1 * d2 * d3))
else:
r = r - ( 4.0 / ( d1 * d2 * d3))
return r
print("PI calculation")
print("One core cpu : ")
start = utime.ticks_ms()
result = 3.0 + PiCalc(0,MaxCount)
print(result)
showTimeLapse(start,MaxCount)
print("\nTwo cores cpu:")
# creation d'une a lock to sync thread
threadLock = _thread.allocate_lock()
# start timer
start = utime.ticks_ms()
#start thread
_thread.start_new_thread(PiCalcThread,(0,MaxCount // 2,threadLock))
#calculation premiere partie en utilisant core 0 (main core)
result = 3.0 + PiCalc(MaxCount // 2, MaxCount)
# wait for the thread to end
while True:
with threadLock:
if threadDone:
break
result = result + threadResult
print(result)
showTimeLapse(start,MaxCount)