📜 ⬆️ ⬇️

Corona SDK exact timer

Hello. In this brief article I will tell you how to make a timer with an acceptable reading accuracy in your application on the Corona SDK. Also consider what are the problems of the standard timer.

The article will solve the following problem: Make an application that will show the elapsed time since the application was turned on with its update 1 time per second.

1. Obvious standard solution.


Create a standard timer and display its ticks.

timeout = 1000 timer.performWithDelay( timeout,function(event) print(event.count) end,0) 

Everything seems to be obvious, but there are features in the work of this solution:
')

2. Good decision.


To solve the problems of the past method, we use the following construction, in this method we use a timer with the maximum possible speed, but the signal for the tick timer will be a calculation based on the exact time source of the system.

 local timeout = 1000-- socket = require "socket" local start_time = socket.gettime()*1000--  ( ) local good_time = 0 timer.performWithDelay( 1,function(event) local new_time = socket.gettime()*1000--   local total_time = new_time - start_time--      local num = math.floor(total_time/timeout)--      timeout if num > good_time then--     good_time = num--  print(good_time) end end,0) 

We analyze the features of this method. Despite the fact that we indicate the frequency of ticks 1ms as described above, the real quanta of ticks will be performed every 16 (33) -50ms, and this will determine the maximum possible error of the above method, the error will vary in the range of 0..50ms from tick to tick, i.e. the frequency of following ticks will be less stable than in the first method, but the magnitude of this error at any distance (even length in years) will be the same, i.e. even in a year, our next tick will have an error within the same limits relative to the very first tick.

3. Verification of results


I will give an example of how you can verify the justice of all the above. The given source will, once per second, display the current time elapsed since the application was turned on for two timers (separately) and show the error accumulated during operation.

 local timeout = 1000 socket = require "socket" local start_time = socket.gettime()*1000--   local good_time = 0--   local bad_time = 0--   --  timer.performWithDelay( timeout,function(event) bad_time = event.count local bad_delta = (socket.gettime()*1000 - start_time) - (bad_time*timeout) print('Bad tick: '..bad_time, 'Delta: '..bad_delta) end,0) --  timer.performWithDelay( 1,function(event) local new_time = socket.gettime()*1000 local total_time = new_time - start_time local num = math.floor(total_time/timeout) if num > good_time then good_time = num local good_delta = (socket.gettime()*1000 - start_time) - (good_time*timeout) print('Good tick: '..good_time, 'Delta: '..good_delta) end end,0) 

Good luck to all!

Source: https://habr.com/ru/post/422443/


All Articles