# 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')
    

def loggerTest():
    t1 = time.ticks_ms()
    f = open('data.log', 'w')
    t2 = time.ticks_ms()
    for idx in range(2000):
        f.write(json.dumps({'index': idx, 'value': 5}) + '\n')
    t3 = time.ticks_ms()
    f.close()
    t4 = time.ticks_ms()
    print(f'total: {t4-t1}, open: {t2-t1}, populate: {t3-t2}, close: {t4-t3}')
    
        
#test1()
#test1()
#test1()
#test2()

loggerTest()
loggerTest()

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