def install(to_install, install_path=None): # Calculate gzip dictionary size to use global gzdict_sz sz = gc.mem_free() + gc.mem_alloc() if sz <= 65536: gzdict_sz = 16 + 12 if install_path is None: install_path = get_install_path() if install_path[-1] != "/": install_path += "/" if not isinstance(to_install, list): to_install = [to_install] print("Installing to: " + install_path) # sets would be perfect here, but don't depend on them installed = [] try: while to_install: if debug: print("Queue:", to_install) pkg_spec = to_install.pop(0) if pkg_spec in installed: continue meta = install_pkg(pkg_spec, install_path) installed.append(pkg_spec) if debug: print(meta) deps = meta.get("deps", "").rstrip() if deps: deps = deps.decode("utf-8").split("\n") to_install.extend(deps) except Exception as e: print("Error installing '{}': {}, packages may be partially installed".format( pkg_spec, e), file=sys.stderr)
async def _memory(self): count = 0 while self.isconnected(): # Ensure just one instance. await asyncio.sleep(1) # Quick response to outage. count += 1 count %= 20 if not count: gc.collect() print('RAM free {} alloc {}'.format(gc.mem_free(), gc.mem_alloc()))
def showOS(): import micropython micropython.mem_info(1) gg.display.fill(0) gg.display.text("Free: " + str(gc.mem_free()), 0, 10) gg.display.text("Alloc: " + str(gc.mem_alloc()), 0, 20) gg.display.show() utime.sleep_ms(5000) micropython.mem_info(1) gc.collect() drawMenu(10)
def main(): # auto collect garbage gc.enable() # Max 1/4 heap used: start auto collect gc.threshold((gc.mem_free() + gc.mem_alloc()) // 4) # start = Start() # s.run() while True: app.run(host='0.0.0.0', debug=True, log=shared._log)
def handle_command(self, args): import gc mem_alloc = gc.mem_alloc() mem_free = gc.mem_free() capacity = mem_alloc + mem_free print(" capacity\tfree\tusage") print(" {}\t{}\t{}%".format(capacity, mem_free, int( ((capacity - mem_free) / capacity) * 100.0))) if "-i" in args: import micropython micropython.mem_info(1)
def system_info(_resPath, _queryParams): respone = {} # curl -i 'http://192.168.10.111/system?memory=' if 'memory' in _queryParams: mem_alloc = gc.mem_alloc() mem_free = gc.mem_free() respone['memory'] = {'mem_alloc': mem_alloc, 'mem_free': mem_free} print(respone) return respone
def send_stats(self): VCP.attach('type', 2) if self.algorithm is not None: VCP.attach('best_operator', self.current_best) VCP.attach('fitness', self.current_best_fitness) VCP.attach('generation', self.algorithm.population.generation) VCP.attach('total_time', self.algorithm.elapsed_time) gc.collect() VCP.attach('free_memory', gc.mem_free()) VCP.attach('alloc_memory', gc.mem_alloc()) VCP.send()
def mem_trace(self, x=None, collect=False): if __debug__: log.debug( __name__, "Log trace: %s, ... F: %s A: %s", x, gc.mem_free(), gc.mem_alloc(), ) if collect: gc.collect()
def mem(level=None): import gc mem_alloc = gc.mem_alloc() mem_free = gc.mem_free() capacity = mem_alloc + mem_free print(" capacity\tfree\tusage") print(" {}\t{}\t{}%".format(capacity, mem_free, int( ((capacity - mem_free) / capacity) * 100.0))) if level: import micropython micropython.mem_info(level)
def init_bufs(): # Calculate gzip dictionary size to use global gzdict_sz, gzdict_buf if gzdict_buf: return sz = gc.mem_free() + gc.mem_alloc() if sz <= 65536: gzdict_sz = 16 + 12 gzdict_buf = bytearray(4096) else: gzdict_buf = bytearray(32768)
def ufree(verbose=False): """In MicroPython report how much RAM memory is free and allocated""" import gc import os F = gc.mem_free() A = gc.mem_alloc() T = F + A P = '{0:.2f}%'.format(F / T * 100) if not verbose: return P return ('Total: {} Free: {} ({})'.format(T, F, P))
def _handler(self, res_path, query_params): response = {} # curl -i 'http://192.168.10.111/system?memory=' if 'memory' in query_params: gc.collect() response['memory'] = { 'mem_alloc': gc.mem_alloc(), 'mem_free': gc.mem_free() } return response
def _idle_thread(self): if self.gc_enable and (self.last_gc == 0 or after(self.last_gc) > GCTIME): gc.collect() gc.threshold(gc.mem_free() // 4 + gc.mem_alloc()) self.last_gc = ticks_us() if self.heartbeat is not None and (self.last_heartbeat == 0 or after(self.last_heartbeat) > HBTIME): if platform == 'pyboard': self.heartbeat.toggle() elif platform == 'esp8266': self.heartbeat(not self.heartbeat()) self.last_heartbeat = ticks_us()
def mem(level=None): import gc mem_alloc = gc.mem_alloc() mem_free = gc.mem_free() capacity = mem_alloc + mem_free print(" capacity\tfree\tusage") print(" {}\t{}\t{}%".format( capacity, mem_free, int(((capacity - mem_free) / capacity) * 100.0))) if level: import micropython micropython.mem_info(level)
def identify_prot(self,lista): tmp1 = (self.trovaflag(lista, 8000, 10000, 4300, 4700)) print("Pos. StartBit",tmp1) #FREE MEMORY gc.collect() mem = gc.mem_free() heap = gc.mem_alloc() if tmp1 is not None: if tmp1 > 0: code = self.prot_nec(lista) return code
def statusSystem(): output = [ sys.version, sys.implementation[0], sys.implementation[1], gc.mem_alloc(), gc.mem_free(), ] for key in MQTTSTATS.keys(): output.append(MQTTSTATS[key]) # return Dictionary return output
def wrapper(*args, **kwargs): memory_alloc = '总内存: %s kb' % str(gc.mem_alloc() / 1024) memory_free = '可用内存: %s kb' % str(gc.mem_free() / 1024) gc.collect() memory_after_collect = '获得: %s kb 可用内存' % str(gc.mem_free() / 1024) print(rainbow(memory_alloc, color='red')) print(rainbow(memory_free, color='green')) print(rainbow(memory_after_collect, color='blue')) func(*args, **kwargs) memory_after_func_excute = '清除 %s 后: %s kb 可用内存' % ( func.__name__, str(gc.mem_free() / 1024)) print(rainbow(memory_after_func_excute, color='red'))
def fill_state(self): state = {} state.update({"time": self.time_mgr.get_sec()}) #state.update({"packjpeg": self.packjpeg}) #state.update({"daymode": self.daymode}) if self.websock_randid != 0: state.update({"rand_id": self.websock_randid}) if self.img is not None and self.cam_err == False: state.update({"expo_code": self.expo_code}) elif self.img is None: state.update({"expo_code": star_finder.EXPO_NO_IMG}) elif self.cam_err: state.update({"expo_code": star_finder.EXPO_CAMERA_ERR}) stable_solution = self.stable_solution() if stable_solution is not None: stable_solution.get_pole_coords() # update time state.update({"solution": stable_solution.to_jsonobj()}) state.update({"star_x": stable_solution.Polaris.cx}) state.update({"star_y": stable_solution.Polaris.cy}) state.update({"pole_x": stable_solution.x}) state.update({"pole_y": stable_solution.y}) state.update({"rotation": stable_solution.get_rotation()}) state.update({"polaris_ra": (stable_solution.polaris_ra_dec[0] * 360.0) / 24.0}) state.update({"pix_per_deg": stable_solution.pix_per_deg}) else: state.update({"solution": False}) if self.stars is not None: star_list = self.stars if len(star_list) > 50: star_list = blobstar.sort_brightness(star_list)[0:50] state.update({"stars": blobstar.to_jsonobj(star_list)}) state.update({"polar_clock": self.time_mgr.get_angle()}) state.update({"max_stars": self.max_stars}) if self.extdisp is not None: state.update({"oled_avail": self.extdisp.oled_ok}) state.update({"gps_avail": self.extdisp.gps_ok}) # diagnostic info state.update({"frm_cnt": self.frm_cnt}) if self.debug: state.update({"diag_cnt": self.diag_cnt}) state.update({"diag_dur_all": self.dur_all}) state.update({"diag_dur_sol": self.solu_dur}) state.update({"diag_mem_alloc": gc.mem_alloc()}) state.update({"diag_mem_free": gc.mem_free()}) if self.img_stats is not None: state.update({"img_mean": self.img_stats.mean()}) state.update({"img_stdev": self.img_stats.stdev()}) state.update({"img_max": self.img_stats.max()}) state.update({"img_min": self.img_stats.min()}) return state
def handle_command(self, args): import gc mem_alloc = gc.mem_alloc() mem_free = gc.mem_free() capacity = mem_alloc + mem_free print(" capacity\tfree\tusage") print(" {}\t{}\t{}%".format( capacity, mem_free, int( ((capacity - mem_free) / capacity) * 100.0))) if "-i" in args: import micropython micropython.mem_info(1)
def ping_check(): global ping_counter, time_last_ping time_now = time.ticks_ms() if time_now > time_last_ping + 1000: time_last_ping = time_now ping_counter -= 1 if ping_counter < 1: ping_counter = keepalive client.ping() gc.collect() print("GC:", gc.mem_free(), gc.mem_alloc()) # 72272 23728
def start(self): print('-----------------------------') print('Initial free: {} allocated: {}'.format(gc.mem_free(), gc.mem_alloc())) print('-----------------------------') self.wifi = WiFi.WiFi(self.SSID, self.password) print('-----------------------------') print('Initial free: {} allocated: {}'.format(gc.mem_free(), gc.mem_alloc())) print('-----------------------------') self.rtc = RTC.RTC() print('-----------------------------') print('Initial free: {} allocated: {}'.format(gc.mem_free(), gc.mem_alloc())) print('-----------------------------') log.info("Download and install update if available") self.download_and_install_update_if_available() print('-----------------------------') print('Initial free: {} allocated: {}'.format(gc.mem_free(), gc.mem_alloc())) print('-----------------------------') self.mqtt = MQTT.MQTT(self.MQTT_broker_IP, self, self.CLIENT_root_topic) print('-----------------------------') print('Initial free: {} allocated: {}'.format(gc.mem_free(), gc.mem_alloc())) print('-----------------------------') self.web = Web.Web(self.wifi.get_IP( )) # Obtain any IP or hostname from wifi initialisation print('-----------------------------') print('Initial free: {} allocated: {}'.format(gc.mem_free(), gc.mem_alloc())) print('-----------------------------') log.info("Program terminated (escaped the loop)")
async def send_response(self, reader, writer): peername = writer.get_extra_info('peername') print('\nRequest from:', peername) await writer.awrite(b'HTTP/1.0 200 OK\r\n') await writer.awrite(b'Content-type: text/html; charset=utf-8\r\n\r\n') await writer.awrite(_HTML_PREFIX) await writer.awrite(b'Your IP: %s port:%s\n' % peername) await writer.awrite(b'\n') method, url, querystring, body = await self.parse_request(reader) parsed_querystring = request_query2dict(querystring) parsed_body = request_query2dict(body) await writer.awrite(b'Method: %s\n' % method) await writer.awrite(b'URL: %s\n' % url) await writer.awrite(b'querystring: %s\n' % querystring) await writer.awrite(b'parsed querystring: %s\n' % parsed_querystring) await writer.awrite(b'body: %s\n' % body) await writer.awrite(b'parsed body: %s\n' % parsed_body) threshold = parsed_querystring.get('threshold') if threshold is None: threshold = parsed_body.get('threshold') if threshold is not None: threshold = int(threshold) await writer.awrite(b'Set gc.threshold() to: %i Bytes\n' % threshold) gc.threshold(threshold) await writer.awrite(_HTML_SUFFIX.format( threshold=gc.threshold() )) alloc = gc.mem_alloc() / 1024 free = gc.mem_free() / 1024 await writer.awrite( b'<p>RAM total: {total:.2f} KB, used: {alloc:.2f} KB, free: {free:.2f} KB</p>'.format( total=alloc + free, alloc=alloc, free=free ) ) await writer.awrite(b'<p>gc.threshold(): %i Bytes</p>' % gc.threshold()) await writer.awrite( b'<p>Render time: %i ms</p>' % utime.ticks_diff(utime.ticks_ms(), self.start_time) ) await writer.awrite(_HTML_FOOTER) await writer.aclose()
async def from_pyboard(self): client = self.client while True: istr = await self.await_obj(20) # wait for string (poll interval 20ms) s = istr.split(SEP) command = s[0] if command == PUBLISH: await client.publish(s[1], s[2], bool(s[3]), int(s[4])) # If qos == 1 only returns once PUBACK received. self.send(argformat(STATUS, PUBOK)) elif command == SUBSCRIBE: await client.subscribe(s[1], int(s[2])) client.subscriptions[s[1]] = int(s[2]) # re-subscribe after outage elif command == MEM: gc.collect() gc.threshold(gc.mem_free() // 4 + gc.mem_alloc()) self.send(argformat(MEM, gc.mem_free(), gc.mem_alloc())) elif command == TIME: t = await client.get_time() self.send(argformat(TIME, t)) else: self.send(argformat(STATUS, UNKNOWN, 'Unknown command:', istr))
def df(): """Get free disk and memory""" st = uos.statvfs('/') _size = int(st[1] * st[2] / 1024) _free = int(st[1] * st[3] / 1024) _used = st[3] / st[2] * 100 print('Flash {:d} / {:d}kB ({:.1f}%)'.format(_free, _size, _used)) gc.collect() _free = gc.mem_free() / 1024 _size = _free + gc.mem_alloc() / 1024 _used = 100 * _free / _size print('RAM {:.1f} / {:.1f}kB ({:.1f}%)'.format(_free, _size, _used))
def run_gc(self): """ Curate the garbage collector. https://docs.pycom.io/firmwareapi/micropython/gc.html For a "quick fix", issue the following periodically. https://community.hiveeyes.org/t/timing-things-on-micropython-for-esp32/2329/9 """ import gc log.info('Start curating the garbage collector') gc.threshold(gc.mem_free() // 4 + gc.mem_alloc()) gc.collect() log.info('Curating the garbage collector finished')
def get(self, data): try: files = uos.listdir("app/resources") except Exception: files = [] mem = { "mem_alloc": gc.mem_alloc(), "mem_free": gc.mem_free(), "mem_total": gc.mem_alloc() + gc.mem_free(), "files": { "app/resources": files }, } sta_if = network.WLAN(network.STA_IF) ifconfig = sta_if.ifconfig() net = { "ip": ifconfig[0], "netmask": ifconfig[1], "gateway": ifconfig[2], "dns": ifconfig[3], } return {"memory": mem, "network": net}, 200
def _handler(self, res_path, query_params): response = {} if self._debug: print("Debug") # curl -i 'http://192.168.10.111/system?memory=' if 'memory' in query_params: response['memory'] = { 'mem_alloc': gc.mem_alloc(), 'mem_free': gc.mem_free() } return response
def wrapper(*args, **kwargs): memory_alloc = 'memory alloced: %s kb' % str(gc.mem_alloc() / 1024) memory_free = 'memory free: %s kb' % str(gc.mem_free() / 1024) gc.collect() memory_after_collect = 'after collect: %s kb available' % str( gc.mem_free() / 1024) print(rainbow(memory_alloc, color='red')) print(rainbow(memory_free, color='green')) print(rainbow(memory_after_collect, color='blue')) func(*args, **kwargs) memory_after_func_excute = 'after %s excuted: %s kb available' % ( func.__name__, str(gc.mem_free() / 1024)) print(rainbow(memory_after_func_excute, color='red'))
def perform(self) : import gc mem_free_before = gc.mem_free() gc.collect() self.mem_free = gc.mem_free() self.mem_alloc = gc.mem_alloc() mem_collected = self.mem_free - mem_free_before if mem_collected < self.min_collected : self.min_collected = mem_collected if self.max_collected < mem_collected : self.max_collected = mem_collected self.sum_collected += mem_collected self.num_collections += 1 return True
def ram(log=False): """Returns free Micropython RAM memory""" gc.collect() freeRam = gc.mem_free() allocatedRam = gc.mem_alloc() totalRam = freeRam+allocatedRam percentage = '{0:.2f} %'.format(freeRam/totalRam*100) if (log): print('■ Micropython RAM') print(' Total : {0:.2f} KB'.format(totalRam/1024)) print(' Free : {0:.2f} KB'.format(freeRam/1024)) print(' Free % : {0}'.format(percentage)) print() return freeRam
def cb_status(): datetime = datenow() chipid = config.get_config('chipid') macaddr = config.get_config('mac') address = config.get_config('address') starttime = config.get_config('starttime') conf = json.dumps(config.get_config(None)) return '<h2>Device %s</h2>' \ '<p>MacAddr: %s' \ '<p>Address: %s' \ '<p>Free Mem: %d (alloc %d)' \ '<p>Date Time: %s' \ '<p>Start Time: %s' \ '</div>' % (chipid, macaddr, address, gc.mem_free(), gc.mem_alloc(), datetime, starttime)
def perform(self): import gc mem_free_before = gc.mem_free() gc.collect() self.mem_free = gc.mem_free() self.mem_alloc = gc.mem_alloc() mem_collected = self.mem_free - mem_free_before if mem_collected < self.min_collected: self.min_collected = mem_collected if self.max_collected < mem_collected: self.max_collected = mem_collected self.sum_collected += mem_collected self.num_collections += 1 return True
def meminfo(display=True): """ Get memory informations """ import gc try: alloc = gc.mem_alloc() free = gc.mem_free() result = b"Mem alloc=%s free=%s total=%s" % (sizeToBytes( alloc, 1), sizeToBytes(free, 1), sizeToBytes(alloc + free, 1)) if display: print(tostrings(result)) else: return result except: return b"Mem unavailable"
def memorySnapshot(location=None): print("\n------memorySnapshot-----") if location: print("Location: {}\n".format(location)) # pylint: disable=E1101 print("Free memory: {} bytes".format(gc.mem_free())) # pylint: disable=E1101 print("Allocated memory: {} bytes".format(gc.mem_alloc())) # pylint: disable=E1101 print("Stack Use: {}".format(micropython.stack_use())) # pylint: disable=E1101 print("Memory Info:") # pylint: disable=E1101 print("-----------------------------") micropython.mem_info(1) print("-----------------------------") print("\n")
def gc_cmd(cli, cmd, rol): before = gc.mem_alloc(), gc.mem_free() gc.collect() after = gc.mem_alloc(), gc.mem_free() yield from cli.writeln('mem_alloc %d, mem_free %d (up %d)' \ % (after[0], after[1], after[1]-before[1]))
def info_cmd(cli, cmd, rol): yield from cli.write('mem_alloc %s, mem_free %s' \ % (gc.mem_alloc(), gc.mem_free())) loop = yield GetRunningLoop(None) yield from cli.write(', qlen %d' % len(loop.q)) yield from cli.writeln('')
from taskmgr import * import taskmgr from opencom import syscall def hello(t:int) -> int: pass print(hello) @taskmgr.auto() def bios(): def syscall_dbg(funcname, *args): result = syscall(funcname, *args) print('>', result) return result syscall_dbg("hello", 3) syscall_dbg("hello2", "world!") syscall_dbg("hello2", "world2!") taskmgr.run(bios) import gc print(gc.collect()) print(gc.mem_alloc(), '/', gc.mem_alloc() + gc.mem_free(), "KB") def main(): pass
import gc gc.threshold((gc.mem_free() + gc.mem_alloc()) // 2) import uos from flashbdev import bdev try: if bdev: vfs = uos.VfsFat(bdev, "") except OSError: import inisetup vfs = inisetup.setup() gc.collect()
async def mem_manage(): # Necessary for long term stability while True: await asyncio.sleep_ms(100) gc.collect() gc.threshold(gc.mem_free() // 4 + gc.mem_alloc())
# basic tests for gc module try: import gc except ImportError: print("SKIP") import sys sys.exit() print(gc.isenabled()) gc.disable() print(gc.isenabled()) gc.enable() print(gc.isenabled()) gc.collect() if hasattr(gc, 'mem_free'): # uPy has these extra functions # just test they execute and return an int assert type(gc.mem_free()) is int assert type(gc.mem_alloc()) is int if hasattr(gc, 'threshold'): # uPy has this extra function # check execution and returns assert(gc.threshold(1) is None) assert(gc.threshold() == 0) assert(gc.threshold(-1) is None) assert(gc.threshold() == -1)
def get_gc_stats(self): import gc return { 'mem_alloc': gc.mem_alloc(), 'mem_free': gc.mem_free() }