# mpy - speed test on file based dictionary logger
# copyright by Anthony Vogelaar, Perth Scotland
# rev 0.10  2026-05-27  initial release

from	machine	import	freq;		freq(240_000_000)
import	os
import	time
import	json

# ================================= utilities ===================================

# get file size in bytes
def fSize(fn='test.log'):
    return os.stat(fn)[6]

# ==================================== logger ===================================

# create a new empty file
def fCreate(fn='test.log'):
    with open(fn, 'w') as f:
        pass
    
    
def fAppend(fn='test.log', idx=0, value=0):
    with open(fn, 'a') as f:
        f.write(json.dumps({'index': idx, 'value': value}) + '\n')
        

#file.flush()
# typically the above line would do. however this is used to ensure that the file is written
#os.fsync(file.fileno())

# ================================== tests ====================================

# create a logger file and append two records
def test1():
    t1 = time.ticks_ms()
    fCreate()
    t2 = time.ticks_ms()
    fAppend()
    t3 = time.ticks_ms()
    fAppend()
    t4 = time.ticks_ms()
    print(f'Create: {t2-t1}, first append: {t3-t2}, second append: {t4-t3} mSec')
    
 
# create a logger file and append 100 records
def test2(n=100):
    t1 = time.ticks_ms()
    fCreate()
    for _ in range(n):
        fAppend()
    t2 = time.ticks_ms()
    print(f'Create file and {n} appends: {t2-t1} mSec')
    

#test1()
#test1()
#test1()
test2()

# ====================================== end ==================================
