timing a function / tasks in lua - timer

I'm trying to determine how long certain statements take to run in my lua code.
My code looks like this:
function test(self)
local timer1
local timer2
local timer3
timer1 = os.time()
print('timer1 start time is:'.. timer1)
--do some stuff.
print( 'Timer1 end time is:' , os.difftime(os.time(), timer1) )
timer2 = os.time()
print('timer2 start time is:'.. timer2)
-- do a lot of stuff
print( 'Timer2 end time is:' , os.difftime(os.time(), timer2) )
timer3=os.time()
print('timer3 start time is:'.. timer3)
-- a lot of processing...
print( 'Timer3 end time is:' , os.difftime(os.time(), timer3) )
end
This is what the output looks like:
timer1 start time is:1401798084
Timer1 end time is: = 0
timer2 start time is:1401798084
Timer2 end time is: = 0
timer3 start time is:1401798084
Timer3 end time is: = 2
Other things I've tried:
Lua - Current time in milliseconds
In the above post, I found this snippet of code:
local x = os.clock()
local s = 0
for i=1,100000 do s = s + i end
os.execute("sleep "..1)
print(string.format("elapsed time: %.2f\n", os.clock() - x))
I added the sleep time... but when it runs, I get the output:
elapsed time: 0.00
I'm clearly doing something wrong. If you have suggestions on how I can fix / improve this, I'm all ears. In the interim, I'm going to revisit the lua site to read up on os.difftime() in case I'm using it incorrectly.
EDIT 1
I changed the test code to look like this:
local x = os.clock()
local s = 0
for i=1,100000 do
s = s + i
os.execute("sleep "..1)
end
print(string.format("elapsed time: %.2f\n", os.clock() - x))
and now I'm getting some values that make sense!

os.clock measures CPU time, not wall time. CPU time does not include time spent in sleep. So the script below still prints zero elapsed time:
local x = os.clock()
os.execute("sleep 60")
print(string.format("elapsed time: %.2f\n", os.clock() - x))
When you move os.execute into the loop, what you're probably measuring is the time to fork a shell. The script below print nonzero elapsed time, even if it is a short loop:
local x = os.clock()
for i=1,1000 do os.execute("true") end
print(string.format("elapsed time: %.2f\n", os.clock() - x))
Finally, you got zero elapsed time in the first loop because Lua is fast. Try changing the limit to 1000000:
local x = os.clock()
local s = 0
for i=1,1000000 do s = s + i end
print(string.format("elapsed time: %.2f\n", os.clock() - x))

This snippet does many rounds of addition and then executes one sleep call for one second.
for i=1,100000 do s = s + i end
os.execute("sleep "..1)
This snippet does the same amount of addition but sleeps for one second each time through the loop.
for i=1,100000 do
s = s + i
os.execute("sleep "..1)
end
That is a big difference.

Related

Get Time Difference without if else statement

C Time Difference
scanf ("%2d %2d", &shours, &sminutes);
printf ("Enter End Time : ");
scanf ("%2d %2d", &ehours, &eminutes);
printf ("\nTIME DIFFERENCE\n");
tohours = ehours - shours;
printf("Hour(s) : %2d", tohours);
tominute = eminutes - sminutes;
printf("\nMinute(s): %2d ", tominute);
How can I make my output like this? When I try to run my code the minutes output is -59 instead of 1 and my hours is the one who got the output "1"
P.S. without using the if else statements
Use (some sort of) timestamps, by turning your hours and minutes variables into one, e.g:
stime = shours * 60 + sminutes;
etime = ehours * 60 + eminutes;
then calculate de difference of that
totime = etime - stime;
then convert that back into hours and minutes
tominutes = totime % 60;
tohours = (totime - tominutes) / 60;
(integer division will take care of rounding down)
Not the most elaborated solution, but I guess you're looking for an beginners-friendly solution
Edit
speaking of beginner-friendly: the % is the modulus operator that returns the remainder of a division. So when you divide 119 by 60 it returns 59. And yes, you could also just get the hours from dividing totime by 60 and let the integer division do the job, but it's nicer (read: clearer to read what's going on) when you divide (totime - tominutes) because it's like the missing part to the line with the modulus

Nested for loop slowing down for unknown reason (autoit)

My code:
Func myFunc()
$lag = 1300
while (1)
MouseMove(870, 189)
sleep(10)
LC(870, 189)
sleep(1200 + $lag)
LC(1010,333)
sleep(100)
RC(826,115)
sleep(50)
LC(870,212)
sleep(50)
send("{ESC}")
sleep(150)
$x = 0
$y = 0
For $i = 0 To 27 Step 1
sleep(11)
MouseClick("left", 1158 + $x ,260 + $y)
$x+=42
if ($x = 168) Then
$x = 0
$y+=36
EndIf
Next
WEnd
EndFunc
The only delay within the for loop is the sleep(11) but it takes about .5 seconds (500ms) for each iteration rather than 11ms + whatever small delay. Also, completely removing the sleep(11) part of the loop still results in an approximately 500ms delay.
Incase anyone was wondering, it's a video game macro; the first part of the while loop opens an interface and sets something up while the second part (the for loop) is suppose to click through the inventory very quickly.
The mouse cursor takes time to move. Set the speed parameter to 0 to make it move instantly
MouseClick("left", 1158 + $x ,260 + $y,1,0)

while loop timer to two decimal places errors

how do I keep the output to two decimal places
no decimal places:
import time
print ("60 SECOND TIMER")
run = input('click ENTER to run')
secs=0
while secs < 60:
print(60 - secs)
time.sleep(1)
secs = secs+1
two decimal places:
import time
print ("60 SECOND TIMER")
run = input('click ENTER to run')
secs=0
while secs < 60:
print(60 - secs)
time.sleep(0.01)
secs = secs+0.01
Quick note: two decimal places starts going mad (ends up with 8 or 9 decimal places
Use the round() function like this:
print(round(60 - secs, 2))
to output the remaining time to two decimal places.
Incidentally, printing it every 10 ms may be a bit optimistic considering that your display is probably only updated 60 times a second, i.e. at 16.67 ms intervals.
try time.sleep(.01 - timer() % .01), to lock the sleep with the timer(). Though it won't help if either time.sleep() or timer() do not support 10ms granularity. It may also depend on how Python interpreter switches between threads (GIL acquire/release) and OS scheduler (how busy the system is and how fast OS can switch between processes/threads).
To pause for a short duration, you could try a busy loop instead:
from time import monotonic as timer
deadline = timer() + .01
while timer() < deadline:
pass
For example, to do something every 10ms for a minute using time.sleep() would probably fail:
import time
from time import monotonic as timer
now = timer()
deadline = now + 60 # a minute
while now < deadline: # do something until the deadline
time.sleep(.01 - timer() % .01) # sleep until 10ms boundary
now = timer()
print("%.06f" % (deadline - now,))
but the solution based on a busy loop should be more precise:
import time
from time import monotonic as timer
dt = .01 # 10ms
time.sleep(dt - timer() % dt)
deadline = now = timer()
outer_deadline = now + 60 # a minute
while now < outer_deadline: # do something until the deadline
print("%.06f" % (outer_deadline - now,))
# pause until the next 10ms boundary
deadline += dt
while now < deadline:
now = timer()

How can I make timeout = 1 second for wait_event_timeout function?

How can I make timeout = 1 second for wait_event_timeout function?
Function : wait_event_timeout (wq,condition,timeout);
How can I make timeout = 1 second.
And if call function like that : wait_event_timeout(queue,flag!='n',30*HZ);
timeout =???
The function wait_event_timeout takes its timeout value in jiffies. Use the constant HZ (number of timer ticks per second) to specify time in jiffies. The expression HZ is the equivalent of one second. The expression 30 * HZ is the equivalent of 30 seconds.
wait_event_timeout (wq,condition,HZ);
wait_event_timeout take timeout in jiffies. and HZ is a defined identifier in linux which means 1 second. So n * HZ means n seconds. Hope now you can convert jiffies time to real world time, like n millisecond = n*HZ/1000
just a remark: take into account that HZ differs from system to system. on most systems / kernels i know Hz is set to 100. so dividing it by 1000 to get milliseconds will always end up with value 0.

References for implementing calendar functionality in an embedded system?

I have an embedded system that currently keeps track of seconds until an event is supposed to occur using a real-time clock driven by a watch crystal.
Now it needs to keep track of the actual date and time. So, I need to be able to calculate the day, month, year, hour, minute and second from a start date/time and offset in seconds.
Could anyone point me in the right direction for taking into account leap years, daylight savings time (DST) and other complications?
Hardware solutions are not an option as this feature is being added to an existing product. An RTC peripheral is integrated into the MCU chosen for the next generation device.
The C Snippets archive has some date and time functions. Update: unfortunately, the C snippets archive is now defunct. I have updated the link to point to the web archive of the page.
See also "Julian day", Wikipedia, which includes formulas for Julian date calculation.
A "julian date calculation" Google search should uncover more if you want to search further.
Calendar code can be a bit complex - if the C runtime library you're using doesn't have such support built-in (and some way to integrate your clock counter to it) you might consider looking at the code in P.J. Plauger's "The Standard C Library" and adapting it to your needs.
I'm bored, couldn't resist trying a solution. Here's a prototype in ruby - should be clear enough to translate to C.
Given offset and a start date stored as: Baseyear, Baseday, Basesec where day 0 = Jan1,
you can calculate the date as
#initialize outputs
year= Baseyear
day = Baseday
sec = Basesec+offset
#days & seconds remaining in the current year
is_leap = is_leap_year(year)
days_remaining = 365+(is_leap ? 1 : 0) - day
secs_remaining = SEC_PER_DAY*days_remaining
#advance by year
while (sec>=secs_remaining)
sec-=secs_remaining
year+=1
is_leap = is_leap_year(year)
days_remaining = 365+(is_leap ? 1 : 0)
secs_remaining = SEC_PER_DAY*days_remaining
day=0
end
#sec holds seconds into the current year, split into days+seconds
day += sec / SEC_PER_DAY
day = day.to_i #cast to int
sec %= SEC_PER_DAY
#lookup month
for i in (0..11)
dpm = DAYS_PER_MONTH[i] # =[31,28,31,30,...]
if (i==1 && is_leap)
dpm+=1
end
if day < dpm
month = i
break
else
day-=dpm
end
end
day+=1 #1-based
hour = sec/3600
min = (sec%3600)/60
sec = sec%60
puts "%s %d, %d # %02d:%02d:%02d" % [MONTHNAME[month],day,year, hour, min, sec]
It should be easy to add a check that the day is between the begin and end days for DST in the current locale, and adjust the hour accordingly.
The following function determines whether a given year is a leap year:
bool is_leap_year(int year)
{
return ((0 == year % 400) || ((0 == year % 4) && (0 != year % 100)));
}

Resources