¡Detente, quédate allí donde estás!


35

Reto

Escriba una función que tome un parámetro: un número entero t. Su función tiene que detener su programa por tsegundos antes de continuar, de manera similar a time.sleep(t)Python y WAIT tBBC BASIC.

No debe utilizar ninguna función integrada de espera ni ninguna función integrada para ejecutar código después de un cierto tiempo, y su programa debe reanudarse después de unos tsegundos.

Para probar su función, hay una tolerancia de 0.1 segundos más o menos que la dada ten su propia máquina: las variaciones entre las computadoras están bien.

Si alguien cuestiona su respuesta, debe proporcionar una prueba fotográfica (capturada) de que su función funciona correctamente para t=1, t=5y t=25. También puede proporcionar los detalles de su computadora para que las personas puedan intentar replicarla en su propia máquina.

Su programa debe ejecutarse y se ejecutará en una computadora cuya velocidad de reloj sea 1.6 GHz o superior.

Victorioso

El programa más corto gana.

Generosidad

Se otorgará una recompensa por el programa más corto que lo detiene sin usar un bucle que verifica cuánto tiempo ha transcurrido. Si está compitiendo por esta recompensa, agregue una nota al pie que diga que su respuesta es para la recompensa.

Tabla de clasificación

/* Configuration */

var QUESTION_ID = 55293; // Obtain this from the url
// It will be like http://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 30525;

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "http://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "http://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });  
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];
  
  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
    });

    var patt = new RegExp(/[Bb]ounty/);
    var res = patt.test(body);
    var bountyyn = "no";

    if (res) {
      bountyyn = "yes";
    }
    
    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
        bounty: bountyyn
      });
    
  });
  
  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;
    
    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link)
                   .replace("{{BOUNTY}}", a.bounty);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    if (/<a/.test(lang)) lang = jQuery(lang).text();
    
    languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang > b.lang) return 1;
    if (a.lang < b.lang) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}
body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 400px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr><td></td><td>Author</td><td>Language</td><td>Size</td><td>Bounty?</td></tr>
    </thead>
    <tbody id="answers">

    </tbody>
  </table>
</div>
<div id="language-list">
  <h2>Winners by Language</h2>
  <table class="language-list">
    <thead>
      <tr><td>Language</td><td>User</td><td>Score</td></tr>
    </thead>
    <tbody id="languages">

    </tbody>
  </table>
</div>
<table style="display: none">
  <tbody id="answer-template">
    <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td>{{BOUNTY}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
<table style="display: none">
  <tbody id="language-template">
    <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>


¿Qué sucede si nuestro lenguaje de programación de elección ( tos ) solo permite obtener el tiempo de precisión de 1 segundo?
Pomo de la puerta

@Doorknob Bueno, la entrada es un número entero, así que está bien
Beta Decay

3
@Doorknob tal vez pueda medir el tiempo de ejecución fuera de su programa, por ejemplo, la salida de depuración y mirar las marcas de tiempo de DebugView.
Thomas Weller

1
¿Es el título y el BBC BASICejemplo una referencia al programa de televisión Sherlock o estoy leyendo demasiado sobre esto?
Fatalize

1
Bueno, al menos te hizo darte cuenta de que tu título era inexacto;)
Fatalize

Respuestas:


36

Código de máquina x86_64, 10 bytes

Hexdump del código:

48 69 c9 ca fc 59 38 e2 fe c3

Código fuente (puede ser ensamblado por ml64Visual Studio):

    TITLE   heh

PUBLIC  mywait
_TEXT   SEGMENT
mywait  PROC
    imul rcx, 945421514
myloop:
    loop myloop
    ret
mywait  ENDP
_TEXT   ENDS
END

Realiza un ciclo vacío, comenzando desde el valor especificado hasta 0. Elegí el multiplicador 945421514 empíricamente por prueba y error, hasta que mi programa de prueba arrojó resultados satisfactorios.

Programa de prueba (espera 10 veces para cada una de las duraciones 1, 5 y 25 segundos):

#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
}

El resultado:

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

Ejecuté este programa en una computadora con Windows que no tiene nada más que hacer. Si ejecuta algunas aplicaciones, los tiempos de espera son más erráticos.

La velocidad de la CPU es de 3.9 GHz. Parece que este código es apenas lo suficientemente bueno para la tecnología de PC actual : si la frecuencia del reloj es de aproximadamente 8.8 GHz, el multiplicador no se ajustará a un int de 32 bits con signo.


PD Como esta respuesta no comprueba cuánto tiempo ha pasado, es un candidato para la recompensa.


44
Esto es genial: D
Beta Decay

12
3900 GHz? Woah! Tal vez MHz?
WayToDoor

2
@WayToDoor fijo! También se agregó información divertida relacionada con eso.
anatolyg

1
La fuente es de 142 bytes, por lo que esta es la respuesta que se debe calificar.
Peter Taylor

3
@PeterTaylor 142 bytes in assembly language; much less in machine code. These are different languages; in my opinion machine code is more fun (however, assembly language would be better in a [restricted-source] challenge). The problem with machine code is that it's non-ASCII, and I think it's not a big problem. A related issue is discussed here; should I (or you) start a discussion on machine code there?
anatolyg

21

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!


Golfed: w()(ping -t$1 0.0) (We must have different pings; mine requires -w$1 and gets a reply from localhost.)
Dennis

Right, then it must only work on OS X with no /dev/lo
georgeunix

Change 0.0 to 1.2 on Linux
georgeunix

On OS X, for w 10, I get 10.02 sec real using time.
georgeunix

w()(ping -w$1 1.2) works like a charm.
Dennis

18

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.

5
Tic ... Toc ... Tic ... Toc
Caridorc

4
If an unassigned function handle is ok too, you could also use @(t)eval('tic;while toc<t,end')
flawr

@flawr Wow! very nice trick, using eval to pack several statements in an anonymous function. Thanks!
Luis Mendo

Yes, that is sometimes a usefull trick, but you still cannot asign values to variables even within eval. I am still working on a way to abuse function handles for recursive functions=) PS: You do not necessarily have to assign a name to the function handle, sometimes you can also pass the handle directly as an argument to another function, e.g. for bsxfun.
flawr

+1, but the anonymous function version does not work in Octave (v 3.8.1). It fails to recognize t variable inside eval.
pawel.boczarski

11

Java, 63 62 bytes

t->{for(long a=System.nanoTime();System.nanoTime()-a<t*1E9;);}

Nothing surprising - just grabs the number of nanoseconds since 1/1/1970 multiple times and checks if a second has passed.

Saved 1 byte thanks to Ypnypn and aditsu.


25
Yay! A Java program below 100 bytes ;D
Beta Decay

5
@BetaDecay Except it's not actually a program.
user253751

1
Didn't somebody mention you can shorten it with a for? for(long a=System.nanoTime();System.nanoTime()-a<t*1E9;);
aditsu

What's with the t->?
Luminous

1
@Luminous It's a lambda expression, commonly used in Java 8.
TNT

8

Batch, 27 Bytes

set /a c=%1+1
ping -n %c% 0

A popular batch trick, since batch didn't have a sleep function.

No loop, so bounty eligible


Golf: set/ac=%1+1 saves 2 bytes.
stevefestl

7

Commodore 64 BASIC, 19 16 bytes

1000 FORI=1TO930*N:NEXT:RETURN

With a call N=<number-of-secods>:GOSUB1000.

However, I cannot provide enough accuracy. Because C64 had about 1 MHz CPU speed, I remember it was good enough to make an empty FOR-NEXT loop 1000 times so that it was about 1 second.

In fact there were two main versions of the machine: PAL 0.985 MHz and NTSC 1.023 MHz (all data from C64 Wikipedia Page). As I had NTSC version, it was required to run loop about 930 times.

Tests with the following program (N seconds, provided by user in INPUT):

10 INPUT N
20 PRINT TI$
30 GOSUB 1000
40 PRINT TI$
50 END
1000 FOR I=1 TO 930*N:NEXT I:RETURN

where TI$ is a system variable containing string (hhmmss format) with time elapsed from last reset (1 second accuracy, however also depending on CPU speed, so this is not quite relevant, because it's the same clock).

enter image description here

Screenshot made with online C64 emulator http://codeazur.com.br/stuff/fc64_final/.

This program (line 1000 only) occupies 16 19 bytes in memory, as tested with PRINT FRE(0)+65535 both before typing the code (38908 bytes) and after (38893 38889 bytes). PRINT FRE(0) returns free memory for BASIC program (it's a negative value and constant 65535 should be added, but in fact it does not matter).

Because this program does not test the time elapsed in a loop, it qualifies for a bounty.


I remember I did perform a test how TI$ variable is accurate and it was about 1 second per ca. 2 hours difference with the reference clock (outside C64), so the accuracy is enough. What I am unsure is the value 950, however, would it be any other value <1000 (which I am sure), it's still the same amount of bytes
Voitcus

I think the J variable should somehow be a part of the real code, not a part of the testing program - so it would wait for N seconds, not just 1 second. I don't know how to integrate it into BASIC's syntax though.
anatolyg

@anatolyg Hm, you are right, it should be something like 1000 FOR I=1 TO N:FOR I=1 TO 950:NEXT I:NEXTJ:RETURN with a call eg. 200 N=5:GOSUB 1000. Also I've noticed the OP required a function. I will try to fix it
Voitcus

@anatolyg I have corrected, it uses GOSUB-RETURN statement, as there are no functions in BASIC
Voitcus

@Voitcus Not even DEF FN like in BBC BASIC?
Beta Decay

7

JavaScript ES6, 50 45 40 bytes

n=>{for(g=Date.now,z=g();z+n*1e3>g(););}

this uses self-executing functions, not sure why +new Date isn't working.


Usage

I've tested this with Safari Nightly but it will also work on Firefox. Tested with:

(
  n=>{for(g=Date.now,z=g();z+n*1e3>g(););}
)(1); // 1 is the delay is seconds
console.log( 'foo' );

You can run it by either surrounding it with parenthesis:

( n=>{for(g=Date.now,z=g();z+n*1e3>g(););} )(5)

Or by naming it:

const wait=n=>{for(g=Date.now,z=g();z+n*1e3>g(););}
wait(5)

Explanation

Here's the main logic behind the program:

function (n) {
    var start = Date.now();   // Save start time (ms)
    while (                   // while is synchronous, it'll block the code execution until it has finished
           start + (n * 1000) // This is the end time (start + delay)
            > Date.now()      // When the current time is 1 ms past the target end time, stop. resuming the code execution
          );
}

The version I'm using uses the same logic:

n=>{ // Function with argument n, { is required if the functions is not just an expression
   for(           // For will also block code execution
                  // This first part is used to define variables
      g=Date.now, // Add an alias for Date.now as "g"
      z=g()       // get current time and store in z
      ;           // Next part, condition
      z + n*1e3   // Target end time, ( start + delay (converted to seconds) ) 1e3 is 1000 but in big e notation
      ;           // Is required for a valid for loop
   );
}

6

CJam, 15

{e3es+{_es>}g;}

This is a block that can be executed or stored into a variable (thus becoming a named function). Dennis and Mr Consensus agree that counting only the block is acceptable :)

Explanation:

e3       multiply the argument by 1000 (to get milliseconds)
es       get the current timestamp in milliseconds
+        add the values, obtaining the stopping time
{…}g     do…while
  _      duplicate the stopping time
  es>    check if we reached that time yet (loop condition)
;        discard the stopping time

Try it online


1
Consensus on Meta is that functions do not have to be named, so I'd argue that a block left on the stack is just as usable as a lambda.
Dennis

6

JavaScript, 68 54 51 42

I think no screenshot is needed. But I suspect you could golf this even more...

New version: I now finally managed to avoid new and using Date twice:

f=t=>{for(x=(d=Date.now)();d()<x+t*1e3;);}

Older versions:

f=t=>{for(x=new Date();(new Date()|0)<x|0+t*1e3;);}

f=t=>{x=(new Date())|0;while((new Date()|0)<x+t*1e3);}

f=t=>{x=new Date().getSeconds();while(new Date().getSeconds()<x+t);}

1
No screenshot is needed now :) Only if someone challenges this program
Beta Decay

5

PHP, 171 177 84 79 65 64 62 bytes

<?php function a($i){for($f=microtime,$e=$f(1)+$i;$f(1)<$e;);}


Usage:
Call the function like so:
php -d error_reporting=0 -r "require 'script.php'; a(5);echo 'Hello, World!';"
Where 5 is the time in seconds the programm should wait before it echoes "Hello, World!".


Explanation:
At first the function gets the current time in milliseconds. Then the function does a loop until the current Time is smaller then the first time + the input. Afterwards "Hello World!" gets echo'ed.

Log:
Saved 113 bytes thanks to Voitcus
Saved 2 bytes thanks to axiac


1
It is - see manual, $get_as_float parameter. Also remove $t, $s - you don't need them (see my code)
Voitcus

1
1e6 = 1000000 one million. echo 1e6; works. But yes - getting as float is number of seconds, so $e=microtime(1)+$i; would be enough
Voitcus

2
A working fiddle for you
Voitcus

1
@Voitcus thanks for your help!
jrenk

1
You can save 2 more bytes (3 bytes on PHP 7): 3v4l.org/fU11Y
axiac

5

Julia, 33 20 bytes

t->watch_file(".",t)

Only works in Julia v0.4 due to changes in the function signature of watch_file. Defines an anonymous function with a single parameter t that (ab)uses the timeout parameter in the watch_file function.

This is a candidate for the bounty!

Demonstration using the Julia REPL:

julia> f=t->watch_file(".",t)
(anonymous function)

julia> @elapsed f(1)
1.002134983

julia> @elapsed f(5)
5.006161965

julia> @elapsed f(25)
25.026096192

Previous answer (33 bytes), also working in Julia stable

t->(b=time();while b+t>time()end)

4

R, 48 bytes

f=function(t){a={g=Sys.time}();while(g()<a+t){}}

Demonstration:

t0 <- Sys.time();f(1); Sys.time() - t0 
## Time difference of 1.000272 secs

t0 <- Sys.time();f(5); Sys.time() - t0 
## Time difference of 5.011189 secs

t0 <- Sys.time();f(25); Sys.time() - t0 
## Time difference of 25.00848 secs

1
I don't think you need to include the f= in the byte count, function snippets are fine.
Solomon Ucko

4

PHP, 39 bytes

function a($a){while($i++<.4583e8*$a);}

(Note that I can actually get this shorter if a full program is required by taking advantage of arguments passed on command line. Down to 35)

<?php while($i++<.4583e8*$argv[1]);

Program used for testing:

<?php function a($a){while($i++<.4583e8*$a);}

record(1);
record(5);
record(25);

function record($t)
{
    $time = microtime_float();
    a($t);
    echo microtime_float() - $time."\n";
}

function microtime_float()
{
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}

Results:

JamesWebster:Documents jameswebster$ php A.php
1.0093479156494
4.9945771694183
24.971961975098

enter image description here


Though I qualify for the bounty, I'm hardly in the running with some of the other entries!


Yep, your byte count is fine
Beta Decay

4

Windows CMD, 22 bytes

ping -w 1000 -n %1 1.1

This uses no loop (label and goto) so this qualifies for the bounty

It sends t pings to to 1.0.0.1 (invalid) and waits for a responce for 1000 ms


3

JavaScript ES6, 40 bytes

t=>{for(t=(d=Date.now)()+t*1e3;d()<t;);}

Tested with the following:

elapsed=(f,t,b=(d=Date.now)())=>(f(t),console.log(d()-b+"ms elapsed")) // accepts func, delay
STOP=t=>{for(t=(d=Date.now)()+t*1e3;d()<t;);}
elapsed(STOP,1)  // prints 1000ms elapsed
elapsed(STOP,5)  // prints 5000ms elapsed
elapsed(STOP,25) // prints 25000ms elapsed

Can you explain what elapsed(STOP, t) does? What are STOP and elapsed?
Beta Decay

elapsed measures the time it took the first argument to run, in this case, STOP, which in turn is just the first code snippet. The second arg to elapsed is the arg passed to STOP.
Dendrobium

3

TI-BASIC (84+SE), 21 bytes

Input method: T:prgmT. This is the closest equivalent of a function in TI-BASIC. Program:

For(A,1,841Ans
End

All accuracy is gained via trial-and-error; timing it with a stopwatch works for all of the given test cases to within a twentieth of a second.

Device information:

RAM FREE   23312
ARC FREE  889802


 TI-84 Plus Silver Edition
          2.55MP
PROD #: 0A-3-02-37
ID: 0A3DC-C3469-FFE8

W00T eligible for a bounty!


1
Did you know: the speed of your calculator's For( loops depends on how many letter variables exist? More variables clog up the VAT and can take up to 20% or so of your time. System variables (e.g. n, Xmin) are immune.
lirtosiast

@ThomasKwa Huh! Interesting. I'll recalibrate with a clean calculator when I have the time to transfer files.
Conor O'Brien

2

Python, 57 bytes

import time
b=time.time
def y(i):
 x=b()
 while x+i>b():x

Call function y()


2

PureBasic, 92 bytes

Procedure z(t)
t=t*1e3+ElapsedMilliseconds()
While t>ElapsedMilliseconds():Wend
EndProcedure

It's the shortest I can think of. I suspect this will be the longest here as well...

To test:

OpenConsole()
i=Val(Input())
s=ElapsedMilliseconds()
z(i)
PrintN(Str(ElapsedMilliseconds()-s))
Input()

2

PowerShell, 75 bytes

Long, descriptive procedure calls. Yay for clarity in a language. :)

function w{param($i);$n=(Get-Date).AddSeconds($i);while($n-gt(Get-Date)){}}

Called within a program with something like

Get-Date
w(15)
Get-Date

Alternatively, if we're allowed external programs to be called instead, we can get down to 59 Bytes with the following:

$n=(Get-Date).AddSeconds($args[0]);while($n-lt(Get-Date)){}

This would be called within a program as follows (presuming the above to be saved as "wait-function.ps1" and saved in the same folder):

Get-Date
& ((Split-Path $MyInvocation.InvocationName) + "\wait-function.ps1 15")
Get-Date

What we save in writing the function/program is more than clobbered by the excess needed to actually execute it, though. Le sigh.


2

Python, 66 bytes

Note, my implementation neither calls an inbuilt time function, nor using scheduling feature.

def S(t):
 try:__import__("Queue").Queue().get(1,t)
 except:pass

And yes, it is eligible for bounty.


Nope, this invalid: You must not use any built in waiting functions or any built in functions for executing code after a certain time
Beta Decay

@BetaDecay: As per my understanding, Queue().get is not a "built in functions for executing code after a certain time". Please explain why this would qualify as one.
Abhijit

Many other answers have code that uses timeouts for other things, so this should be fine too.
Solomon Ucko


2

Pyth, 19 bytes

Late entry but after finding .d0 in the docs last night I decided to give it a go.

DCNK.d0W<-.d0KNJ1))

Defines a function which loops until the time elapsed is N seconds.

Try it here.


Nice. I got DCNJ+.dZN#Ig.dZJB)), which is also 19 bytes.
hakr14

2

RProgN 2, 13 bytes

°°°)*™+]³]™>:

Explained

°°°)*™+]³]™>:
°°°             # Push 3 tens to the stack.
   )*           # Get the product of the entire stack, including the implicit input. This is the shortest way to multiply the input by 1000.
     ™+         # Add it to the current time in miliseconds.
       ]        # Duplicate it to use as a (throwaway) conditional.
        ³   :   # Create a function using the next 3 concepts, and while the top of the stack is truthy, execute it.
         ]      # Duplicate the target time
          ™>    # Is it larger than the current time?

The bounty specifically says "without using a loop checking how much time has elapsed", which this does not do. This sets a target time, and keeps checking if it's passed that target time, thus it's eligible for the bounty.

Try it online!


1

Tcl, 53 bytes

proc W t {while "\[clock mil]-[clock mil]<$t*1e3" {}}

Try it online!

Explained

Command clock milliseconds can be reduced to clock mil, with escaped 1st bracket, it'll be interpreted at each loop, and w/o just once. As it measures milliseconds, we need to multpily by 1000 or 1e3 which saves 1 Byte.


1

C# (Visual C# Interactive Compiler) + /u:System.Threading, 36 bytes

x=>new SemaphoreSlim(0).Wait(x*1000)

Try it online!

Creates a semaphore with no capacity and tries to get it for the specified number of seconds.

I realize I am "wait"ing on something here. To me this seems more like the ping/timeout solution as opposed to Thread.Sleep. The code tries to get a resource that it cannot get and stops trying after a limit.

===

Below is a variation that starts a Task with an infinite loop, then waits for it to complete with a timeout. All required namespaces are included by default, but the solution is a few bytes longer than the one above.

C# (Visual C# Interactive Compiler), 40 bytes

x=>Task.Run(()=>{for(;;);}).Wait(x*1000)

Try it online!


0

05AB1E, 22 bytes

žcžb60*+[Džcžb60*+αIQ#

Try it online.

NOTE: Depending on how many microseconds in the current second have already passed, the tolerance might be slightly larger than 0.1 sec. But since almost halve the answers have similar issues, I figured it's allowed.

Explanation:

05AB1E doesn't have any builtins for the current time. It does however have a builtin for the current year/month/day/hours/minutes/seconds/microseconds as separated builtins. Since only using seconds can potentially wrap around from 59 to 0 causing issues, I need both the minutes and seconds, making the code even longer than most answers in non-codegolfing languages unfortunately.

žc                # Push the current seconds
  žb              # Push the current minutes
    60*           # Multiply it by 60
       +          # Add them together
[                 # Start an infinite loop:
 D                #  Duplicate the initial (minutes*60 + seconds) from before the loop
  žcžb60*+        #  Push the current (minutes*60 + seconds) again
          α       #  And take the absolute difference between the two
           IQ     #  And if this is equal to the input:
             #    #   Stop the infinite loop

0

SmileBASIC, 20 bytes

INPUT T
DIALOG"",,,T

Opens a dialog box that closes automatically after T seconds. I'm not sure if this counts as a "built in waiting function", but I think this is just as valid as using ping.

An alternative 37-byte program which definitely isn't cheating:

INPUT T
FADE.,T*60WHILE FADECHK()WEND

Causes the screen fade color to change to 0 (alpha=0,red=0,green=0,blue=0) (no effect) gradually over T seconds, then waits for that animation to finish.

Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.