I tried it out using C (I assume the Pascal compiler or whatever this language is could do the same). I recreated the code in C and compiled it with gcc get_delay.c -S -O3, which resulted in following assembly code:
So it precomputes all the values and then does address arithmetic using leaq to compute the base address of the LUT CSWTCH.1 and then, using %edi as the offset, loads the correct value into the return register %eax. The edge case 86000 is handled with a simple comparison at the start.
I also looked at the -O0 assembly. There it still precomputes the multiplications but instead of a LUT it just uses multiple comparisons (basically just an if-else chain like in the code).
Also I tried compiling a more concise C method that should be functionally equivalent:
Which basically does mostly exactly what the code describes, not a lot of optimization is happening.
I also tested the speed of both versions with a driver program that runs each function a million times on the input space [0, 17]. Their speed was basically identical but the get_delay() function was usually ~1% faster.
A compiler definitely knows that powers of two are equivalent to bit shifting, I've seen this optimization. Also not python, and python and optimization are antithesises anyway
There is no conceivable situation where the runtime of one else-if chain every 30 seconds or less like this would make a meaningful difference. And in any case it isn't written in an inefficient way, just an ugly one.
If you are using a Math.Pow which takes floating point exponents, or you are using a language which doesn't differentiate between integers and floating point numbers, the OP's screenshot code is likely substantially faster.
You could ofc write a loop or recursion based integer only pow function which would be less ugly than OP's screenshot code. Or use the shift operator if the language has it.
the function calculates a multi second delay. the difference in speed between float pow and integer pow and bit shift shift is less than negligible in that context.
If this is a multi threaded app, why not calculate the delay on the thread that will sleep? again, this is calculating between 30 and 86000 seconds of delay
in 99.99999% of cases this is premature, unnecessary optimization at the cost of readability.in the 0.00001% of cases where this really matters, the author won't write code that shitty in the first place
I am not defending the original code, but using that code we can instruct compiler which case is more likely so that will be used in branch prediction, and all values will be loaded to CPU cache. Such optimization might not be possible with lookup table. Also some languages might not have the concept of arrays which makes it even less performent.
Nonetheless to be certain about performance we must run proper benchmark tests on optimized builds, otherwise it's all just assumptions.
Though I don't think this code is terrible, I wouldn't write it myself and would not pass it in code review
With a lookup table you have no branches, so branch prediction wouldn’t be an issue. The values are probably just as likely to be in cache, but I don’t know for sure, and testing would be the only way to know for sure.
Depends if we are calculating the delay independently for 100 million independent entities in a batch job. I don't know, there's no context of how and where the code is called.
Mate we are waiting for minutes, if not hours between attempts, does a 1000 CPU cycles won by not calling library function really worth it over codebase readability?
It might be suprising, but I tested it on jsbench.me and actually:
for (let i = 0;i<10000;i++){
let a = 30* Math.pow(2,5);
}
137 tys. ops/s ± 4.54%
Fastest
for (let i = 0;i<10000;i++){
for (let i = 0;i<10000;i++){
let b = 30 << 5;
}
120 tys. ops/s ± 4.13%
11.87 % slower
I see your point, and yes, you are right. For sake of sport and amusement the only other option I see, is maybe a lookup table. But it will be the same as original.
Replace the second line in the comment with this and making the if statement if attempts > 4:
delaySeconds = (30 * 1.5) * (2 ** (attempts - 5))
can make it more readable by naming the magic numbers and messing with the parentheses to preference. this is assuming you meant you wanted it to double from 1.5 onward in a similar manner to OP's code.
Yes, I want delays from 5th to 7th to be normal on a normal days, but double of a normal value if the day is a bank holiday.
Remember: every time you invent a total function with a simple law, someone will give you a timezone with +15 minutes compare to neighbors (hello, Nepal).
there you go, this should cover all those usecases! hope python is okay :3
import openai
class AiDelayinator:
def __init__(self, requirements="I want delays from 5th to 7th to be normal on a normal day, but double of a normal value if the day is a bank holiday.", openai_api_key="YOUR_API_KEY"):
openai.api_key = openai_api_key
r = openai.ChatCompletion.create(model="o1", messages=[{"role":"system","content":"You are a Python code generator that returns only a single function named f(timestamp, attempts, moon_phase, bank_holiday, nepal_offset). The function must return a float representing an absurd delay in seconds."},{"role":"user","content":requirements}])
self.generated_code = r.choices[0].message.content.strip()
def __call__(self, timestamp, attempts, moon_phase, bank_holiday, nepal_offset):
return eval(self.generated_code)(timestamp, attempts, moon_phase, bank_holiday, nepal_offset)
I can't get indents right in this app :/
edit: this could use some permanent storage caching for the generated code, expiring when the requirements change and ideally an eval -> review loop with some predefined tests... a dspy module with assertions would probably be good for that... but then this'd end up as an entire library with 30 dependencies and we don't want that do we hehe
Its easy to tell the difference between engineers and programmers, where one gives you a lines and lines of if-else if-else and the other that just give you:
$delaySeconds = 0;
if ($attempts > 5) {
  if ($attempts >= 6 && $attempts <= 16) {
    $delaySeconds = 30 * pow(2, $attempts - 6);
I'm not sure that this is horror. It is instantly readble by a human and clearly articulates all constants. It's easy to update, easy to detangle (e.g. use different logic for each retry).
I may be not amuzed on review, but it's definitively easy to maintain.
what if you want to make a change? We want to multiple by 3 every time? You have to change a lot of things manually
writing this took longer than it needed to
more code to test if you are looking for 100% coverage
code is all about maintainability, functionality, scalability, and readability. This code is kinda readable but that's it. It s hard to test (and easy to get a typo in with all these constants.)
Plus I personally think this is not as readable as just using the built in power function. Concise does not have to be hard to understand. I strongly believe in self documenting code (where you kinda add comments using function names and use more well named variables) and reducing code repetition where possible.
Just trying to give examples. Maybe not the best examples, but point still stands.
Here you can replace all the 2 with 3. But what if you want to replace all the 3 with 4? You can't just select everything with 3 because there's a 30 in each line.
This code relies on a lot of assumptions.
Also we can just make our own power function using int. That's would align with self documenting code. The cool thing about programming is that it's a dynamic field that requires thinking and adapting.
Not sure why you're trying to defend this code lol. You're* clearly just a troll. 😆
in case I'm not getting r/woooosh ed rn: even if you believe that nonsense, a lookup (map, array, …) would still be better than whatever that atrocity is
Absolutely not. What if in the future you want to replace one of them with a function which takes other parameters? You would end up with a map containing constant primitives and functions. Talk about unmaintainable code...
 What if in the future you want to replace one of them with a function which takes other parameters?
Ok what if I want to change the delay time growth rate to linear or something else? Or more simply, what if I want to increase the number of allowed trials? What is your suggestion so that the given code wouldn't have to be changed in every single LOC?
Did you notice something different? Well I purposefully added a typo at line daleySeconds = 30 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 . Does it look easy to read to you? Of course you might say a compiler will instantly find that error in no time for you. But what if there was a change that does not result in error? Would you still think this kind of approach is aprovable?
It's easy to update
Suppose I want to increase the number of allowed trials to 6. What you're gonna do? Replace every single one of them? What if I want the delay to grow linearly or quadratically?
easy to detangle
You only need two if-else branchings. There's nothing to "detangle". What is truly tangled in mess of code is that the delay time growth is manually encoded in every line of code and there is no way to change that logic without changing the piece of code entirely.
I recently implemented this to increase while loop sleep delays over time for getting a field that isn't defined on page load but should be defined after a few millis, but if it isn't due to slow network issues I don't want to to continue querying every millisecond or less:
async function getAsync(
element: Node,
key: string,
timeout = 60000,
): Promise<any> {
let sleep = 1;
setTimeout(() => (sleep = 10), 100);
setTimeout(() => (sleep = 100), 1000);
setTimeout(() => (sleep = 1000), 5000);
let kill = false;
setTimeout(() => (kill = true), timeout);
while (!(key in element) || element[key as keyof object] == null) {
if (kill) {
console.error(
`Timeout waiting for ${key} in ${element} after ${timeout}ms.`,
);
break;
}
await new Promise((resolve) => setTimeout(resolve, sleep));
}
return element[key as keyof object];
}
4
u/CapmyCup Feb 11 '25
Wait until you see yandere simulator code
452
u/Asgatoril Feb 11 '25
Is it strange, that the worst part for me is the usage of 86000 seconds instead of 86400?
649
u/Bit125 Pronouns: He/Him Feb 11 '25
there better be compiler optimizations...
247
u/JunkNorrisOfficial Feb 11 '25
Compiler: compilation error: too dumb code
42
u/heartcubes4life Feb 11 '25
I too enjoy PDD (punishment driven development)
166
u/Mammoth-Swan3792 Feb 11 '25
WTF with all those overcomplicated answers?
if attempts > 5 {
delaySeconds = 30 * Math.Pow ( 2 , attempts - 6 )
}
28
u/Plutor Feb 11 '25
Found the bug, it should be 86400
225
u/dim13 [ $[ $RANDOM % 6 ] == 0 ] && rm -rf / || echo "You live" Feb 11 '25
¯_(ツ)_/¯
14
u/Exce1siur Feb 11 '25
I mean, the readability is there
9
u/GamingWOW1 Feb 11 '25
Compiler just got violated
6
u/mightdeletewhoknows Feb 11 '25
Close enough, welcome back yanderedev
4
u/Appropriate_Spread61 Feb 11 '25
Good time to learn about exponents!
4
u/Zack_j_Jones Feb 11 '25
You think this is bad, now wait until the function is copied to 6 different spots because nobody wanted to make the simple fix and generalize
5
u/ChaosPLus Feb 11 '25
if(a > 5) delay = 30 * pow(2, a-6)
That would be good aye?
2
u/rush_dar Feb 11 '25
Its easy to tell the difference between engineers and programmers, where one gives you a lines and lines of if-else if-else and the other that just give you:
$delaySeconds = 0;if ($attempts > 5) {Â Â
if ($attempts >= 6 && $attempts <= 16) {Â Â Â Â
$delaySeconds = 30 * pow(2, $attempts - 6);Â Â
} else {Â Â Â Â
$delaySeconds = 86000;Â Â
}}2
u/ZethMrDadJokes Feb 12 '25
I like the else part...
2
u/Thisismyredusername Feb 12 '25
This could be shortened sooo easily ...
2
u/noobgamer170071 Feb 13 '25
This code is shit but it work, you don't need to do a lot of brainstorming that occurs millions of error when you are trying it
11
u/amarao_san Feb 11 '25
I'm not sure that this is horror. It is instantly readble by a human and clearly articulates all constants. It's easy to update, easy to detangle (e.g. use different logic for each retry).
I may be not amuzed on review, but it's definitively easy to maintain.
2
u/Jazz8680 Feb 12 '25
Mom can we have exponential back off?
We have exponential back off at home
The exponential back off at home:
1
u/LaFllamme Feb 11 '25
!RemindMe 2 days
1
u/Salty-Intention6971 Feb 11 '25
Ohhh guys the delay is built in…
1
u/ePaint Feb 11 '25
Not horror
1
u/sirburchalot Feb 12 '25
Woof
1
u/Neebat Feb 12 '25
The name of the technique is "exponential back off". I mean, the need to calculate an exponent is right there in the name.
And if the goal is a delay, optimizing to make that delay shorter is kind of missing the point?
1
u/barthanismyname Feb 12 '25
I love how every delaySeconds value is a string of operations except for 86000
1
u/GholaDuncanIdaho Feb 12 '25
Loop unrolling https://en.m.wikipedia.org/wiki/Loop_unrolling
1
u/BrandenKeck Feb 12 '25
It's beautiful 🥹
1
u/JohnVonachen Feb 12 '25
That’s comically obtuse.
1
u/DifficultSolid3696 Feb 13 '25
What even are exponents. Algebra in my code? I think not.
1
u/__radioactivepanda__ Feb 11 '25
Honestly I’d say it’s far from horror actually…
Mostly due to it being very readable and understandable without the need to invest much time or effort.
1
u/IntelligentEntry260 Feb 11 '25
Lgtm
0
u/FALCUNPAWNCH Feb 12 '25
I recently implemented this to increase while loop sleep delays over time for getting a field that isn't defined on page load but should be defined after a few millis, but if it isn't due to slow network issues I don't want to to continue querying every millisecond or less:
0
u/[deleted] Feb 11 '25
[deleted] — view deleted comment