get obj.speed in realtime

I need function to get object speed in reealtime as function inside float script.
I already found scripts which can do this but in animation timeline + I don`t know how to
translate this to scripted controler. Can anybody can help me with this. Below is code for
calculating object speed at frames.

prePos = at time (currentTime - 1t) $.pos
nextPos = at time (currentTime + 1t) $.pos
d = distance prePos nextPos
v = d*4800/2 -- unit:inch/s
v = v*2.54/1000 -- unit:m/s
v = v*60*60/1000 -- unit:km/h