What is the impact of a function on execution speed? - python-3.x

Fairly new to python and working on an application where speed is critical - essentially in a race to book reservations online as close to 7AM as possible. Was trying to understand the impact on execution speed that a function call has, so i developed a very simple test: count to 1,000,000 and time start and end using both in line and a called function. However, the result i get says that the function takes about 56% of the time that the inline code takes. I must be really be missing something. Can anyone explain this please.
Code:
import time
def timeit():
temp = 0
while temp < 10000000:
temp += 1
return
time1 = time.time()
temp = 0
while temp < 10000000:
temp += 1
time2 = time.time()
timeit()
time3 = time.time()
temp = 0
while temp < 10000000:
temp += 1
time4 = time.time()
timeit()
time5 = time.time()
print("direct took " + "{:.16f}".format(time2 - time1) + " seconds")
print("indirect took " + "{:.16f}".format(time3 - time2) + " seconds")
print("2nd direct took " + "{:.16f}".format(time4 - time3) + " seconds")
print("2nd indirect took " + "{:.16f}".format(time5 - time4) + " seconds")
results:
direct took 1.6094279289245605 seconds
indirect took 0.9220039844512939 seconds
2nd direct took 1.5781939029693604 seconds
2nd indirect took 0.9375154972076416 seconds
I apologize for missing something silly that i must have done?

Related

Groovy not converting seconds to hours properly

I have an integer that is:
19045800
I tried different code:
def c = Calendar.instance
c.clear()
c.set(Calendar.SECOND, 19045800)
echo c.format('HH:mm:ss').toString()
String timestamp = new GregorianCalendar( 0, 0, 0, 0, 0, 19045800, 0 ).time.format( 'HH:mm:ss' )
echo timestamp
Both return 10:30:00
19045800 seconds is supposed to be over 5000 hours. What am I doing wrong?
I'm not sure what you are looking for. But if your requirement is to calculate the number of hours, minutes, and the remainder of seconds for given seconds following code will work.
def timeInSeconds = 19045800
int hours = timeInSeconds/3600
int minutes = (timeInSeconds%3600)/60
int seconds = ((timeInSeconds%3600)%60)
println("Hours: " + hours)
println("Minutes: " + minutes)
println("Seconds: " + seconds)
You're attempting to use a Calendar, but what you're actually discussing is what Java calls a Duration – a length of time in a particular measurement unit.
import java.time.*
def dur = Duration.ofSeconds(19045800)
def hours = dur.toHours()
def minutes = dur.minusHours(hours).toMinutes()
def seconds = dur.minusHours(hours).minusMinutes(minutes).toSeconds()
println "hours = ${hours}"
println "minutes = ${minutes}"
println "seconds = ${seconds}"
prints:
hours = 5290
minutes = 30
seconds = 0

creating a system that 'unlocks' when the timer reaches 0

I'm working on a script where there is this timer and a user enters a duration e.g 2days: 2hoursd : 2minutes: 2seconds and when the timer hits 0 the word "unlocked" appears
I am absolutely lost and have no clue where to begin
ide show some code but I'm honestly lost
the user enters a duration
timer ticks down
timer reaches 0
word "unlocked" appears
The start_timer function starts a blocking timer which sleeps for one second each, until the defined duration has been reached. Additionally, if you run the script as main, it asks for user input to set the timer.
import datetime
import time
def start_timer(days=0, hours=0, minutes=0, seconds=5):
t0 = datetime.datetime.now()
delta = datetime.timedelta(days=days, seconds=seconds, minutes=minutes,
hours=hours)
t1 = datetime.datetime.now()
while (t1 - t0) < delta:
time.sleep(1)
t1 = datetime.datetime.now()
print("Unlocked")
if __name__ == "__main__":
days = float(input("Days? "))
hours = float(input("Hours? "))
minutes = float(input("Minutes? "))
seconds = float(input("Seconds? "))
start_timer(days=days, hours=hours, minutes=minutes, seconds=seconds)

ClientResponseError on edit_message coroutine after around 1234 edits

I have setup a bot to delete thousands upon thousands of messages, it's around 20,000 messages, my code works and is deleting messages, I also have a message that's constantly being edited to tell me how many messages have been deleted out of total, which also works but after a while I get a ClientResponseError exception from that line and it halts my message deleting loop, why is this happening? and can I just use a try except and then pass so my loop doesn't halt? I'm not exactly sure what that exception even is, the documentation doesn't have anything on it
Code:
counter = 0
begin, end = around_month(month, year)
tmsg = await Client.send_message(ctx.message.channel, 'Progress: 0/' + str(number))
estimate = number * 1.5
estimate = estimate / 60
estimate = estimate / 60
estimate = round(estimate, 2)
await Client.send_message(ctx.message.channel, 'Estimated time: ' + str(estimate) + 'hours')
async for x in Client.logs_from(channelid, limit = number, after=begin, before=end):
counter += 1
await Client.edit_message(tmsg, 'Progress: ' + str(counter) + '/' + str(number))
await Client.delete_message(x)
await asyncio.sleep(1.5)
await Client.send_message(ctx.message.channel, 'Operation completed! ' + 'Cleared: ' + str(counter) + ' items')

Retrieve decimals only from a variable

I'm making a distance/time used calculator where i'm trying to separate whole hours and minutes.
Code:
if (hours >= 1)
{
minutes = Number((hours-int.(hours))*60);
timeTxt.text = String(int.(hours)+" hours & "+(minutes)+" minutes");
}
else
{
timeTxt.text = String((hours*60).toFixed(0)+" minutes");
}
the "else" one is working and prints minutes only. But I can't get the first if statement to work. Trying to print "x hours & x minutes".
Getting this message in output:
TypeError: Error #1123: Filter operator not supported on type class int.
at Rutekalkulator2_fla::MainTimeline/calculate()
Couldn't you do something like:
(pseudocode)
double tmp = math.floor(yournumber);
yournumber = yournumber - tmp;
And that'll make your number be just the decimal part.
Besides that, I'm not really sure what your question is.
Convert everything to minutes then try the following:
timeTxt.text = String( totMinutes / 60 + ":" + totMinutes % 60);
// output 06:36
timeTxt.text = String( totMinutes / 60 + " hours and " + totMinutes % 60 + " minutes");
// output 6 hours and 36 minutes
I'm not fluent in Actionscript but if the modulo works the same as it does in other languages this should work for you.

Nested Parallel While Loops

I am trying to run two while loops in parallel for the purpose of data acquisition.
This program will run for "n" num_trials with specific trial duration for each trial.
During each trial, the program will collect data while keeping track of the trial duration. For example, the first trial starts collecting data at 1 seconds and stops at 10 seconds. This process will repeat for the rest number of trials
How can I run both while loops in parallel?
Basically, I just want a method that will break the second while loop once the specified trial duration is complete?
Thanks in advance.
count = 0;
num_trials = 5; % Number of Trials = 5 Trials
trial_duration = 10; % Trial Duration = 10 Seconds
global check
check = 0;
% Number of Trials
for i = 1:num_trials
fprintf('Starting Trial %i\n', i);
t_start = tic;
% Start counting and Collecting Data
while toc(t_start) < trial_duration
% Data Collection
while (check ~= 1)
count = count +1;
end
end
fprintf('Ending Trial %i\n', i);
end
Have you tried using a single loop with && ?
while (toc(t_start) < trial_duration) && (check ~= 1)
% Data Collection
count = count +1;
end

Resources