35
\$\begingroup\$

Challenge

Write a function which takes one parameter: an integer t. Your function has to stop your program for t seconds before continuing, similar to time.sleep(t) in Python and WAIT t in BBC BASIC.

You must not use any built in waiting functions or any built in functions for executing code after a certain time, and your program must resume after t seconds.

For testing your function, there is tolerance of 0.1 seconds more or less than the given t on your own machine: variances between computers are fine.

If your answer is challenged by anyone, you must provide photographic (screenshotted) proof that your function works correctly for t=1, t=5 and t=25. You may also provide the details of your computer so people can try to replicate it on their own machine.

Your program should and will be run on a computer whose clock speed is 1.6 GHz or higher.

Winning

The shortest program wins.

Bounty

A bounty will go out to the shortest program which stops the program without using a loop checking how much time has elapsed. If you are in the running for this bounty, add a footnote saying that your answer is for the bounty.

Leaderboard

/* 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>

\$\endgroup\$
  • \$\begingroup\$ What if our programming language of choice (cough cough) only supports getting the time to 1-second accuracy? \$\endgroup\$ – Doorknob Aug 25 '15 at 21:19
  • \$\begingroup\$ @Doorknob Well the input is an integer, so that's fine \$\endgroup\$ – Beta Decay Aug 25 '15 at 21:34
  • 3
    \$\begingroup\$ @Doorknob perhaps you can measure execution time outside of your program, e.g. debug output and look at the time stamps of DebugView. \$\endgroup\$ – Thomas Weller Aug 25 '15 at 22:07
  • 1
    \$\begingroup\$ Is the title and the BBC BASIC example a reference to the tv show Sherlock or am I reading too much into this? \$\endgroup\$ – Fatalize Aug 26 '15 at 7:48
  • 1
    \$\begingroup\$ Well at least it made you realize that your title was inexact ;) \$\endgroup\$ – Fatalize Aug 26 '15 at 8:18

27 Answers 27

36
+50
\$\begingroup\$

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.

\$\endgroup\$
  • 4
    \$\begingroup\$ This is cool :D \$\endgroup\$ – Beta Decay Aug 26 '15 at 11:52
  • 12
    \$\begingroup\$ 3900 GHz ? Woah ! Maybe MHz ? \$\endgroup\$ – WayToDoor Aug 26 '15 at 12:40
  • 2
    \$\begingroup\$ @WayToDoor Fixed! Also added some fun info related to that. \$\endgroup\$ – anatolyg Aug 26 '15 at 13:02
  • \$\begingroup\$ If I understand your approach correctly: if the computer is devoting only half processor time to the program, the waiting times would be double? \$\endgroup\$ – Luis Mendo Aug 26 '15 at 14:02
  • 3
    \$\begingroup\$ @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? \$\endgroup\$ – anatolyg Aug 26 '15 at 21:28
21
\$\begingroup\$

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!

\$\endgroup\$
  • \$\begingroup\$ Golfed: w()(ping -t$1 0.0) (We must have different pings; mine requires -w$1 and gets a reply from localhost.) \$\endgroup\$ – Dennis Aug 27 '15 at 6:41
  • \$\begingroup\$ Right, then it must only work on OS X with no /dev/lo \$\endgroup\$ – georgeunix Aug 27 '15 at 6:42
  • \$\begingroup\$ Change 0.0 to 1.2 on Linux \$\endgroup\$ – georgeunix Aug 27 '15 at 6:43
  • \$\begingroup\$ On OS X, for w 10, I get 10.02 sec real using time. \$\endgroup\$ – georgeunix Aug 27 '15 at 6:44
  • \$\begingroup\$ w()(ping -w$1 1.2) works like a charm. \$\endgroup\$ – Dennis Aug 27 '15 at 6:44
18
\$\begingroup\$

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.
\$\endgroup\$
  • 5
    \$\begingroup\$ Tic ... Toc ... Tic ... Toc \$\endgroup\$ – Caridorc Aug 26 '15 at 13:14
  • 4
    \$\begingroup\$ If an unassigned function handle is ok too, you could also use @(t)eval('tic;while toc<t,end') \$\endgroup\$ – flawr Aug 26 '15 at 14:47
  • \$\begingroup\$ @flawr Wow! very nice trick, using eval to pack several statements in an anonymous function. Thanks! \$\endgroup\$ – Luis Mendo Aug 26 '15 at 15:59
  • \$\begingroup\$ 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. \$\endgroup\$ – flawr Aug 26 '15 at 17:41
  • \$\begingroup\$ +1, but the anonymous function version does not work in Octave (v 3.8.1). It fails to recognize t variable inside eval. \$\endgroup\$ – pawel.boczarski Aug 27 '15 at 10:12
11
\$\begingroup\$

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.

\$\endgroup\$
  • 25
    \$\begingroup\$ Yay! A Java program below 100 bytes ;D \$\endgroup\$ – Beta Decay Aug 25 '15 at 22:28
  • 5
    \$\begingroup\$ @BetaDecay Except it's not actually a program. \$\endgroup\$ – immibis Aug 26 '15 at 6:01
  • 1
    \$\begingroup\$ Didn't somebody mention you can shorten it with a for? for(long a=System.nanoTime();System.nanoTime()-a<t*1E9;); \$\endgroup\$ – aditsu Aug 26 '15 at 9:30
  • \$\begingroup\$ What's with the t->? \$\endgroup\$ – Luminous Aug 27 '15 at 12:17
  • 1
    \$\begingroup\$ @Luminous It's a lambda expression, commonly used in Java 8. \$\endgroup\$ – TNT Aug 27 '15 at 12:48
8
\$\begingroup\$

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

\$\endgroup\$
  • \$\begingroup\$ Golf: set/ac=%1+1 saves 2 bytes. \$\endgroup\$ – stevefestl May 20 '17 at 15:13
7
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ 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 \$\endgroup\$ – Voitcus Aug 26 '15 at 13:37
  • \$\begingroup\$ 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. \$\endgroup\$ – anatolyg Aug 26 '15 at 15:27
  • \$\begingroup\$ @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 \$\endgroup\$ – Voitcus Aug 26 '15 at 15:30
  • \$\begingroup\$ @anatolyg I have corrected, it uses GOSUB-RETURN statement, as there are no functions in BASIC \$\endgroup\$ – Voitcus Aug 26 '15 at 15:56
  • \$\begingroup\$ @Voitcus Not even DEF FN like in BBC BASIC? \$\endgroup\$ – Beta Decay Aug 26 '15 at 22:59
7
\$\begingroup\$

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
   );
}
\$\endgroup\$
6
\$\begingroup\$

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

\$\endgroup\$
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ – Dennis Aug 26 '15 at 4:54
6
\$\begingroup\$

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);}
\$\endgroup\$
  • 1
    \$\begingroup\$ No screenshot is needed now :) Only if someone challenges this program \$\endgroup\$ – Beta Decay Aug 25 '15 at 21:14
5
\$\begingroup\$

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

\$\endgroup\$
  • 1
    \$\begingroup\$ It is - see manual, $get_as_float parameter. Also remove $t, $s - you don't need them (see my code) \$\endgroup\$ – Voitcus Aug 26 '15 at 8:47
  • 1
    \$\begingroup\$ 1e6 = 1000000 one million. echo 1e6; works. But yes - getting as float is number of seconds, so $e=microtime(1)+$i; would be enough \$\endgroup\$ – Voitcus Aug 26 '15 at 9:06
  • 2
    \$\begingroup\$ A working fiddle for you \$\endgroup\$ – Voitcus Aug 26 '15 at 9:09
  • 1
    \$\begingroup\$ @Voitcus thanks for your help! \$\endgroup\$ – jrenk Aug 26 '15 at 9:13
  • 1
    \$\begingroup\$ You can save 2 more bytes (3 bytes on PHP 7): 3v4l.org/fU11Y \$\endgroup\$ – axiac Aug 26 '15 at 11:10
5
\$\begingroup\$

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)
\$\endgroup\$
4
\$\begingroup\$

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
\$\endgroup\$
  • 1
    \$\begingroup\$ I don't think you need to include the f= in the byte count, function snippets are fine. \$\endgroup\$ – Solomon Ucko Dec 23 '17 at 19:47
4
\$\begingroup\$

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!

\$\endgroup\$
  • \$\begingroup\$ Yep, your byte count is fine \$\endgroup\$ – Beta Decay Aug 27 '15 at 13:45
4
\$\begingroup\$

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

\$\endgroup\$
3
\$\begingroup\$

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
\$\endgroup\$
  • \$\begingroup\$ Can you explain what elapsed(STOP, t) does? What are STOP and elapsed? \$\endgroup\$ – Beta Decay Aug 26 '15 at 8:44
  • \$\begingroup\$ 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. \$\endgroup\$ – Dendrobium Aug 26 '15 at 14:39
3
\$\begingroup\$

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!

\$\endgroup\$
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ – lirtosiast Oct 1 '15 at 23:48
  • \$\begingroup\$ @ThomasKwa Huh! Interesting. I'll recalibrate with a clean calculator when I have the time to transfer files. \$\endgroup\$ – Conor O'Brien Oct 1 '15 at 23:51
2
\$\begingroup\$

Python, 57 bytes

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

Call function y()

\$\endgroup\$
2
\$\begingroup\$

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()
\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ Nope, this invalid: You must not use any built in waiting functions or any built in functions for executing code after a certain time \$\endgroup\$ – Beta Decay Aug 27 '15 at 9:30
  • \$\begingroup\$ @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. \$\endgroup\$ – Abhijit Aug 27 '15 at 14:04
  • \$\begingroup\$ Many other answers have code that uses timeouts for other things, so this should be fine too. \$\endgroup\$ – Solomon Ucko Dec 23 '17 at 20:03
2
\$\begingroup\$

Hassium, 55 Bytes

func w(t){p=time().second;while((p+t)>time().second)0;}

Run and see expanded: http://HassiumLang.com/Hassium/index.php?code=9f4e2bdb292b14b150fba63677a11a79

\$\endgroup\$
  • \$\begingroup\$ Just checking, when was this language first created? \$\endgroup\$ – Beta Decay Oct 2 '15 at 16:48
  • \$\begingroup\$ August 9th 2015 \$\endgroup\$ – Jacob Misirian Oct 3 '15 at 17:40
2
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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!

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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!

\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.