I didn't think sleep() paid any attention to wall clock time. There is the problem that the OS won't necessarily wake up your process after the exact amount of time passed to sleep() though. And that would be compounded by two calls to sleep().
Easy solution, just multiply the numbers by 1000 before passing them to sleep, that way you have an entire second of error built in. Just divide by 1000 after you're done!
Faster than what, bogosort? It advertises O(n) sometimes, but when you're scheduling threads, the internal thread scheduling algorithm would start to become O(nlog(n)).
Edit to add: if you have a list of many duplicates, your sleepsort may instead be emulating bucketsort, but it'll still be less efficient.
I’m currently building out part of our app with an editable section that saves when changes are made so I was debouncing saves by 2 seconds. If someone hit a button to submit though, I thought I needed the saves to complete because when the submission was faster than the save, the upstream copy no longer existed and would throw errors. I didn’t realize lodash returned a cancel function with its denounce, so my solution was to add the submission to the debounce which felt like ages waiting for 3-4 seconds after submission for it to take. After a day and a half of trying to juggle the network calls I finally found that all I had to do was cancel the debounce and fire off the submission immediately
I have heard of people needing to add delay so they could have a loading animation, that way the user believes its doing something. Maybe something like that?
Intentionally slow down run time by introducing wait points.
Helps if you have dependent applications/need to ensure a cache is clear before proceeding.
Or as some commentary have pointed out, you can manually slow the application down, then when you boss asks you to improve performance you can "re-hash some old code" an hey Presto! It runs faster.
"We've survived Y2K38. Our programmer has assured me that he's learned his lesson and we will have no further problems on Y292B277M026K596. His future employment depends on it."
I don't know if python works this way, but I've always understood sleep to mean "block for at least the provided amount of time" not "block for exactly the provided amount of time" so if this works at all, it's pure luck.
What’s funny is that sleep is guaranteed to be at minimum what you ask, but nowhere are you guaranteed that your thread resumes after your sleep at the moment you requested.
Instead of just adding the integers together. They go ahead and sleep for that amount of time, then calculate how much time had passed. For instance instead of just doing 3+4, they take the current time, wait for 3 minutes and 4 minutes then get the time difference between the first gotten current time and the current time Also, happy cake day!
In this programming language, all commands are determined by how much time has passed http://danieltemkin.com/Esolangs/TimeOut/ (and if you click away to another tab while it runs, it often misfires)
It's a little of both; kind of like schizophrenia. This is basically what happens when a depth-first machine learning algorithm gets possessed by the devil.
def add(x, y):
""" adds two integers """
result = x
if y >= 0:
while y:
result +=1
y -= 1
return result
else:
while y:
result -= 1
y += 1
return result
It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.
For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.
/u/Azazel_711, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.
But I think the programmer wanted the function to run slow. Your solution is probably much to fast. Please add some sleep statements to random positions in your code to meet the requirements.
def add(x, y):
""" adds two integers and has a 67% chance to sleep a random time """
result = x
if y >= 0:
while y:
if random.random() >= 0.33: sleep(random.randint(1,30))
result +=1
y -= 1
return result
else:
while y:
if random.random() >= 0.33: sleep(random.randint(1,30))
result -= 1
y += 1
return result
A smarter solution should be to get the current microseconds, then use usleep to wait until a new second just starts to minimise potential risks of incorrect answers.
But would it? .time() returns the number of seconds since the epoch (2070-01-01 00:00:00.00). This is not affected by the calendar. However, it could be affected by changes to the system clock (manually changing the date/time or NTP adjustments). A better option would be .monotonic(), but not for the reason you mentioned.
.time()might be impacted by leap seconds. Per the Python standard its not guaranteed to be handled in any specific manner. So if you called time 1 second apart the difference might be 1, 0, or -1 seconds. .monotonic() is just as bad because its only guaranteed to go forward. Sometimes it just stops so it can match up with regular time, or it speeds up. You're better off grabbing the system clock CLOCK_MONOTONIC_RAW.
I've had to time lot's of code, getting seconds correct tends to be an incredible pain in the ass.
Sleep isn't even guaranteed to work at exact times. sleep() can go long based on how the program is scheduled and it can go short in other circumstances.
Actually, it won't work at all in the microsecond range. And not well in the millisecond range either.
At a general level, on a loaded system, threads are not woken after precisely the programmed duration - it will be at a random time after that.
Second, you need to consider the OS implementation of preemptive multitasking. This mechanism influences everything around threads, calls to sleep and other blocking calls to the OS (such as disk access, network or even virtual memory).
The OS has a (typical, configurable) time of 1ms that processes run on the CPU before the OS can remove the process in favour of another thread. This means that, if you are a running this on a CPU and there are other processes occupying a CPU core, that process gets to run in 1ms timeslices until the OS decides to awake the sleeping thread. The upshot is, on even a lightly loaded system, the accuracy of a sleep() is around 1ms. Maybe a bit better. On a heavily loaded system, don't expect any accuracy at all.
So you could consider using a real-time OS - inherently you'll have much better accuracy on sleep(). However Python itself can't guarantee anything given the garbage collector that can lock the Python memory at any time.
The ellipsis was meant to imply no, not really. But they recognized that it's only good for positive integers. I'm pretty sure this code is a joke and the author doesn't actually think sleep() is a good way to add.
First, we store the value for NOW(), then we sleep (let's say first 1, then 2), then we substract our stored value from NOW(), which will be exactly the amount of time we slept.
1.1k
u/Ochidi Feb 06 '21
“Hey, Bob, can you add two 8 digit numbers together for me?”
“Sure, I’ll tell you the answer next year.”
339
u/MatthewRPG576 Feb 06 '21
Sleepsort anyone?
123
u/highnastic Feb 06 '21
What the fuck, thats some next Level way of thinking
92
u/0bel1sk Feb 07 '21
is this one of those devs that builds slowness in code, takes a couple sprints to “refactor “, and just removes his sleeps.
62
u/inthemindofadogg Feb 06 '21
Should definitely plug this into production
PR Approved ✅
39
u/[deleted] Feb 07 '21
unit tests take 45 minutes to pass
45
u/knightttime Feb 07 '21
Image Transcription: Code
I'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!
14
u/[deleted] Feb 06 '21
but why
10
u/mywholefuckinglife Feb 07 '21
in doing some Googling I saw someone describe: Create and compile a random program.
Run the random program on the input array.
If the program produces sorted output, you are done.
Else repeat from the beginning.
I think that's really funny but I wanna see an implementation so bad
9
u/Flyspeck101 Now where's that function declaration Feb 07 '21
And then it hits the 32-bit limit and crashes
8
u/root54 Feb 07 '21
I don't know if python works this way, but I've always understood sleep to mean "block for at least the provided amount of time" not "block for exactly the provided amount of time" so if this works at all, it's pure luck.
5
u/whatnameshoulditake Feb 06 '21
That's pure genius
5
u/americk0 Feb 07 '21
It's got a O(1) time complexity. Ship it!
4
u/[deleted] Feb 06 '21
epiiiic
4
u/vonci Feb 07 '21
Thanks! I hate it
4
u/AnnoyedVelociraptor Feb 07 '21
What’s funny is that sleep is guaranteed to be at minimum what you ask, but nowhere are you guaranteed that your thread resumes after your sleep at the moment you requested.
3
u/Hozerino Feb 07 '21
Just like the good old Sleep Sort
3
u/Cobyh7 Feb 07 '21
Can someome explain this to my smooth brain?
3
u/A_GratefulDude Feb 07 '21
Pretty sure the + operator in JavaScript handles all addition this way
3
u/Toxic-Sky Feb 07 '21
I wish there were an easier way of adding two numbers together, but here we are...
7
u/plun1331 Feb 06 '21
last I checked that sleeps for 2 positive integers
2
u/[deleted] Feb 07 '21
Both. If I got this into production, I would document it & show it off as often as possible.
2
u/[deleted] Feb 07 '21
My brain cells are bleeding.
2
u/garfieldsheets Feb 07 '21
In this programming language, all commands are determined by how much time has passed http://danieltemkin.com/Esolangs/TimeOut/ (and if you click away to another tab while it runs, it often misfires)
2
u/XnaK_ Feb 07 '21
This is wrong in so many ways that I love it
2
u/theabbiee Biggus Dickus Oct 23 '21
In a world where more runtime is considered efficient
3
u/nati9931 Feb 07 '21
Do you really need the
sleepfunc? Python is already slow2
u/[deleted] Feb 07 '21
It's a little of both; kind of like schizophrenia. This is basically what happens when a depth-first machine learning algorithm gets possessed by the devil.
1
u/critc Feb 07 '21
Good grief
1
u/Needleroozer Feb 07 '21
For multiplication just loop num1 times and sleep(num2) each loop.
1
u/RandomTyp Feb 07 '21
why did they do a single line comment like this, they could have just used a hash-mark
1
u/Azazel_711 Feb 07 '21 edited Feb 07 '21
Couldn't you just
1
u/pierce-mason Feb 07 '21
I think it is both lol
1
u/ImplosiveTech Feb 07 '21
hey i recognize that ide
1
u/[deleted] Feb 10 '21
Time complexity taken to a whole nother level
1
u/muffinnosehair Feb 11 '21
This needs an implicit declaration, along the lines of random. You know, just in case someone forgets to provide input for one of the arguments...
1
u/Peculiarination Feb 20 '21
Take your upvote...
0
u/jaimeLeJambonneau Feb 07 '21
My immediate reflex would be to git blame and hire henchmen to beat the crap out of the author. I just hope this is a joke. It's a joke, right?
-26
u/CaydendW Feb 06 '21
The worst part is using triple quotes for comments instead of hashes.
0
u/[deleted] Feb 06 '21
[deleted] — view deleted comment
0
u/[deleted] Feb 07 '21
[deleted] — view deleted comment