Stop, stand there where you are!
x86_64 machine code, 10 bytes
Hexdump of the code:
48 69 c9 ca fc 59 38 e2 fe c3
Source code (can be assembled by ml64
of Visual Studio):
TITLE heh
PUBLIC mywait
_TEXT SEGMENT
mywait PROC
imul rcx, 945421514
myloop:
loop myloop
ret
mywait ENDP
_TEXT ENDS
END
Performs an empty loop, starting from the specified value down to 0. I chose the multiplier 945421514 empirically by trial and error, until my test program output satisfactory results.
Test program (waits 10 times for each of the durations 1, 5 and 25 seconds):
#include <stdio.h>
#include <time.h>
extern "C" void mywait(int);
int main()
{
int durations[] = {1, 5, 25};
for (int duration: durations)
{
for (int i = 0; i < 10; ++i)
{
clock_t before = clock();
mywait(duration);
clock_t after = clock();
printf("%f\n", (after - before) / (double)CLOCKS_PER_SEC);
}
}
getchar(); // now take a screenshot
}
The result:
1.003000
1.000000
1.004000
1.006000
1.005000
0.998000
0.995000
1.000000
1.005000
1.004000
4.999000
5.003000
5.035000
5.010000
4.992000
5.003000
5.003000
5.019000
5.026000
4.989000
25.041000
24.993000
25.049000
24.988000
25.038000
24.948000
25.007000
25.014000
25.053000
25.021000
I ran this program on a Windows computer that has nothing else to do. If it runs some applications, the waiting times are more erratic.
The CPU speed is 3.9 GHz. It seems that this code is barely good enough for current PC technology - if the clock frequency is about 8.8 GHz, the multiplier will not fit into a signed 32-bit int.
P.S. As this answer doesn't check how much time has passed, it is a candidate for the bounty.
Bash, 29 25 24 23 19 bytes
w()(ping -t$1 1.2)
Accuracy test (time
) where $1
= 1 second:
real 0m1.012s
user 0m0.001s
sys 0m0.002s
Thanks Dennis for shaving the byte count down to 19 from 23!
EDIT: I've changed the IP to avoid ping
on Linux pinging 0.0.0.0, which is the loopback device.
How this works
ping
has a default timeout of 1 second, so, when contacting an IP address which does not exist, ping can't continue until either the time out has passed, or it has got a reply from the IP.
-t
tells ping
to try $1
number of times on this fake IP address, forcing ping
to take $1
seconds to complete the ping.
It's eligible for the bounty! No loop!
Matlab, 33 bytes
function f(t)
tic;while toc<t,end
Or you can also use this in Octave: try it online
Matlab, 31 bytes
As suggested by @flawr, it can be done with an anonymous function (it should be assigned a name in order to use it):
@(t)eval('tic;while toc<t,end')
Example:
>> f=@(t)eval('tic;while toc<t,end');
>> tic, f(2), toc
Elapsed time is 2.000323 seconds.