PikaStdLib Examples


PikaStdLib Examples

This document introduces PikaStdLib’s memory checking (MemChecker) and system object usage. Examples reference: multiple MemChecker usages in doc/pikapython.com/examples/ and builtins/write_issue.py, Class/main.py.

Module Introduction

PikaStdLib provides memory monitoring and system-level functions. Built-in example:

#!pika
import PikaStdLib
mem = PikaStdLib.MemChecker()
mem.now()   # Current memory (if supported)
mem.max()   # Max memory (if supported)
#!pika

Or use getNow()/getMax() (follows actual API):

#!pika
from PikaStdLib import MemChecker as mem
m = mem().getNow()
# Execute some operation
m2 = mem().getNow()
print('mem: ', m2 - m)
#!pika

API Overview

  • MemChecker(): Create memory checking object.
  • getNow() / now(): Get current memory usage (unit depends on platform, like kB).
  • getMax() / max(): Get maximum memory usage since running.

Example Code

Memory Monitoring (write_issue excerpt)

#!pika
from PikaStdLib import MemChecker as mem
a = open(".test.py", "wb")
m0 = mem().getNow()
for i in range(1000):
    n = a.write(b'# print(r_data[0])\n# print(r_data[1])\n\n# import _thread\n# import')

assert n == 64
m1 = mem().getNow()
for i in range(1000):
    n = a.write(b'import osTimer33332 cnt=0332 cnt1=033332 def test_cb(arg):332global cnt332cnt+=1332123123123123231231')

assert n == 101
m2 = mem().getNow()
a.close()
print('PASS')
print('mem: ', m2 - m0)
#!pika

Note: Call getNow() before and after loop writing, use difference to observe memory impact of this code segment.

Extend by Inheriting MemChecker (Class/main.py excerpt)

#!pika
import PikaStdLib

class mymem(PikaStdLib.MemChecker):
    def mymax(self):
        print('mem used max: ' + str(self.getMax()) + ' kB')

mem = mymem()
mem.mymax()
#!pika

Note: Subclass inherits MemChecker and encapsulates getMax(), convenient for unified viewing of max memory in scripts.

Notes

  • Specific method names like getNow/getMax and now/max follow device firmware and PikaStdLib version, please follow actual API.
  • Memory units are platform-defined (commonly kB), can be used for relative comparison, not suitable for absolute values.