Experiments using the ESP32, based on projects and demos shared by members of Savage///Chats.
(https://savagecircuits.com/wp-content/uploads/2024/03/ESP32-Experiments_00.jpg)
CLICK HERE TO GO TO THIS PROJECT ON THE SAVAGE///CIRCUITS WEBSITE (https://savagecircuits.com/arduino-nano-esp32-experiments/)
This is not truly specific to the Nano ESP32 so if the topic is moved that's ok but I did do the following test on a Nano ESP32. Also I don't claim the complete code to be mine, I wish I could find the link again, but it showcases two forms of optimization using what are called decorators in micro python. The decorators are called @micropython.native and @micropython.viper , the viper results are phenomenal. The code runs three separate methods on a prime number and prints the timed results at the end.
import time
import machine
def test_regular(num):
if num == 1:
# 1 is defined as not prime
return False
elif num > 1:
# check for factors
for i in range(2, num):
if (num % i) == 0:
# if factor is found, this is not a prime number
return False
# No factors found - number is prime
return True
@micropython.native
def test_native(num):
if num == 1:
# 1 is defined as not prime
return False
elif num > 1:
# check for factors
for i in range(2, num):
if (num % i) == 0:
# if factor is found, this is not a prime number
return False
# No factors found - number is prime
return True
@micropython.viper
def test_viper(num:int) -> bool:
if num == 1:
# 1 is defined as not prime
return False
elif num > 1:
# check for factors
for i in range(2, num):
if (num % i) == 0:
# if factor is found, this is not a prime number
return False
def compareRunTime(num):
start_time = time.ticks_ms()
output1 = test_regular(num)
elapsed = time.ticks_ms() - start_time
print(f"Regular {elapsed/1000} ms")
regular_time = elapsed
start_time = time.ticks_ms()
output1 = test_native(num)
elapsed = time.ticks_ms() - start_time
native_time = regular_time/elapsed
print(f"Native {elapsed/1000} ms ~{round(native_time,1)} times faster")
start_time = time.ticks_ms()
output1 = test_viper(num)
elapsed = time.ticks_ms() - start_time
viper_time = regular_time/elapsed
print(f"Viper {elapsed/1000} ms ~{round(viper_time,1)} times faster")
compareRunTime(71569) # This is a prime number
These are the results of the test on my system
>>> %Run -c $EDITOR_CONTENT
MPY: soft reboot
Regular 0.265 ms
Native 0.113 ms ~2.3 times faster
Viper 0.017 ms ~15.6 times faster
>>>
EDIT : here is a link to some useful Viper info https://github.com/micropython/micropython/wiki/Improving-performance-with-Viper-code
Very interesting stuff. More things to try when I get back to this project.