Stop, stand there where you are!

35

5

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>

Beta Decay

Posted 2015-08-25T21:04:42.503

Reputation: 21 478

What if our programming language of choice (cough cough) only supports getting the time to 1-second accuracy?

– Doorknob – 2015-08-25T21:19:32.127

@Doorknob Well the input is an integer, so that's fine – Beta Decay – 2015-08-25T21:34:16.053

But what about the rule "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."? – Doorknob – 2015-08-25T21:36:02.870

3@Doorknob perhaps you can measure execution time outside of your program, e.g. debug output and look at the time stamps of DebugView. – Thomas Weller – 2015-08-25T22:07:17.517

1Is the title and the BBC BASIC example a reference to the tv show Sherlock or am I reading too much into this? – Fatalize – 2015-08-26T07:48:36.553

@Fatalize Nope, not at all :)

– Beta Decay – 2015-08-26T08:12:21.410

1Well at least it made you realize that your title was inexact ;) – Fatalize – 2015-08-26T08:18:14.140

@Fatalize Exactly :D – Beta Decay – 2015-08-26T08:18:41.280

@Justin Only if you don't use Timer.schedule – Beta Decay – 2015-08-26T16:19:42.820

@BetaDecay Nice song! :-) – Luis Mendo – 2015-08-28T00:02:03.573

@LuisMendo Thank you :D – Beta Decay – 2015-08-28T07:33:42.817

@BetaDecay Thanks for the edit! – Luis Mendo – 2015-09-07T09:23:54.063

@LuisMendo Oh, uh no problem :) – Beta Decay – 2015-09-07T09:25:31.997

Answers

36

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.

anatolyg

Posted 2015-08-25T21:04:42.503

Reputation: 10 719

4This is cool :D – Beta Decay – 2015-08-26T11:52:14.933

123900 GHz ? Woah ! Maybe MHz ? – WayToDoor – 2015-08-26T12:40:04.387

2@WayToDoor Fixed! Also added some fun info related to that. – anatolyg – 2015-08-26T13:02:44.003

If I understand your approach correctly: if the computer is devoting only half processor time to the program, the waiting times would be double? – Luis Mendo – 2015-08-26T14:02:25.277

@LuisMendo Yes, and it's never exactly half, so waiting times would be very inexact. – anatolyg – 2015-08-26T14:09:52.037

Although I'm loosing the opportunity to receive bonus for my answer, I think fair play is important and I advice you mark your answer as the program does not test how much time has elapsed

– Voitcus – 2015-08-26T14:37:27.100

@anatolyg I'm not sure it really answers the challenge then? "Stop your program for t seconds before continuing" – Luis Mendo – 2015-08-26T18:18:50.167

@LuisMendo Depends on how you want to interpret the rules. It seems that your interpretation is "... in any conditions" while my interpretation is "... in any favourable conditions". Here in PPCG, we are pretty much used to make strong assumptions (e.g. using the default-int rule in C), which are absolutely unacceptable in modern software. In addition, OP's intent seems to be that solutions depending on CPU speed are OK: "...on your own machine: variances between computers are fine..." – anatolyg – 2015-08-26T18:59:08.450

1The source is 142 bytes, so that's what this answer should be scored as. – Peter Taylor – 2015-08-26T20:50:47.890

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 – 2015-08-26T21:28:26.250

Basically I'm saying the same thing as the comment to the answer you link to. – Peter Taylor – 2015-08-29T18:23:41.633

The right tool for the job. – jqblz – 2015-10-02T15:26:39.733

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!

georgeunix

Posted 2015-08-25T21:04:42.503

Reputation: 3 169

Golfed: w()(ping -t$1 0.0) (We must have different pings; mine requires -w$1 and gets a reply from localhost.) – Dennis – 2015-08-27T06:41:02.203

Right, then it must only work on OS X with no /dev/lo – georgeunix – 2015-08-27T06:42:42.943

Change 0.0 to 1.2 on Linux – georgeunix – 2015-08-27T06:43:12.440

On OS X, for w 10, I get 10.02 sec real using time. – georgeunix – 2015-08-27T06:44:21.600

w()(ping -w$1 1.2) works like a charm. – Dennis – 2015-08-27T06:44:23.660

This is clever :D – Beta Decay – 2015-08-27T09:31:18.830

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.

Luis Mendo

Posted 2015-08-25T21:04:42.503

Reputation: 87 464

5Tic ... Toc ... Tic ... Toc – Caridorc – 2015-08-26T13:14:40.843

4If an unassigned function handle is ok too, you could also use @(t)eval('tic;while toc<t,end') – flawr – 2015-08-26T14:47:01.433

@flawr Wow! very nice trick, using eval to pack several statements in an anonymous function. Thanks! – Luis Mendo – 2015-08-26T15:59:43.660

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 – 2015-08-26T17:41:04.543

+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 – 2015-08-27T10:12:09.833

@pawel.boczarski Thanks! Corrected – Luis Mendo – 2015-08-27T10:15:41.037

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.

TNT

Posted 2015-08-25T21:04:42.503

Reputation: 2 442

25Yay! A Java program below 100 bytes ;D – Beta Decay – 2015-08-25T22:28:28.847

5@BetaDecay Except it's not actually a program. – user253751 – 2015-08-26T06:01:41.190

1Didn't somebody mention you can shorten it with a for? for(long a=System.nanoTime();System.nanoTime()-a<t*1E9;); – aditsu quit because SE is EVIL – 2015-08-26T09:30:16.093

What's with the t->? – Luminous – 2015-08-27T12:17:50.610

1

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

– TNT – 2015-08-27T12:48:08.673

Java has lambda? Java is becoming more like Python :D – Zizouz212 – 2015-08-28T02:34:44.263

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

tomkandy

Posted 2015-08-25T21:04:42.503

Reputation: 167

Golf: set/ac=%1+1 saves 2 bytes. – stevefestl – 2017-05-20T15:13:05.020

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
   );
}

Downgoat

Posted 2015-08-25T21:04:42.503

Reputation: 27 116

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.

Voitcus

Posted 2015-08-25T21:04:42.503

Reputation: 755

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 – 2015-08-26T13:37:48.953

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 – 2015-08-26T15:27:14.783

@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 – 2015-08-26T15:30:28.647

@anatolyg I have corrected, it uses GOSUB-RETURN statement, as there are no functions in BASIC – Voitcus – 2015-08-26T15:56:30.467

@Voitcus Not even DEF FN like in BBC BASIC? – Beta Decay – 2015-08-26T22:59:14.657

@BetaDecay Yes, there is DEF FN, however, it's only mathematical function. It does not allow to have any statements within. I think GOSUB is the only equivalent for the function that does not return value only. – Voitcus – 2015-08-27T08:22:12.737

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);}

flawr

Posted 2015-08-25T21:04:42.503

Reputation: 40 560

1No screenshot is needed now :) Only if someone challenges this program – Beta Decay – 2015-08-25T21:14:47.080

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

aditsu quit because SE is EVIL

Posted 2015-08-25T21:04:42.503

Reputation: 22 326

1Consensus 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 – 2015-08-26T04:54:10.160

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

jrenk

Posted 2015-08-25T21:04:42.503

Reputation: 451

I would change while($t<$i) (one byte less). Also because if something goes wrong and PHP process would be delayed, it will not go to an endless loop. Also, why not use microtime(true)? This removes all this list() staff. I would do this like function a($i){$e=microtime(true)+$i*1e6;while(microtime(true)<$e);} (not tested). Also you could change true to 1. Probably you could use $u+.0 instead of (float)$u. – Voitcus – 2015-08-26T08:33:19.943

@Voitcus microtime(1) should be documented somewhere ... Thanks for the help! – jrenk – 2015-08-26T08:41:48.363

1

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

– Voitcus – 2015-08-26T08:47:35.880

@Voitcus I think the "*1e6" is not right – jrenk – 2015-08-26T08:57:47.160

11e6 = 1000000 one million. echo 1e6; works. But yes - getting as float is number of seconds, so $e=microtime(1)+$i; would be enough – Voitcus – 2015-08-26T09:06:36.797

2

A working fiddle for you

– Voitcus – 2015-08-26T09:09:38.113

1@Voitcus thanks for your help! – jrenk – 2015-08-26T09:13:51.773

1

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

– axiac – 2015-08-26T11:10:58.770

More two bytes if change <?php to <? – Voitcus – 2015-08-26T12:00:36.097

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)

kvill

Posted 2015-08-25T21:04:42.503

Reputation: 329

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

jbaums

Posted 2015-08-25T21:04:42.503

Reputation: 181

1I don't think you need to include the f= in the byte count, function snippets are fine. – Solomon Ucko – 2017-12-23T19:47:36.237

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!

James Webster

Posted 2015-08-25T21:04:42.503

Reputation: 2 809

Yep, your byte count is fine – Beta Decay – 2015-08-27T13:45:15.840

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

Grant Davis

Posted 2015-08-25T21:04:42.503

Reputation: 693

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

Dendrobium

Posted 2015-08-25T21:04:42.503

Reputation: 2 412

Can you explain what elapsed(STOP, t) does? What are STOP and elapsed? – Beta Decay – 2015-08-26T08:44:00.223

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 – 2015-08-26T14:39:20.557

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!

Conor O'Brien

Posted 2015-08-25T21:04:42.503

Reputation: 36 228

1Did 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 – 2015-10-01T23:48:25.417

@ThomasKwa Huh! Interesting. I'll recalibrate with a clean calculator when I have the time to transfer files. – Conor O'Brien – 2015-10-01T23:51:05.000

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!

ATaco

Posted 2015-08-25T21:04:42.503

Reputation: 7 898

2

Python, 57 bytes

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

Call function y()

Blue

Posted 2015-08-25T21:04:42.503

Reputation: 26 661

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()

Fozzedout

Posted 2015-08-25T21:04:42.503

Reputation: 121

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.

AdmBorkBork

Posted 2015-08-25T21:04:42.503

Reputation: 41 581

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.

Abhijit

Posted 2015-08-25T21:04:42.503

Reputation: 2 841

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 – 2015-08-27T09:30:12.233

@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 – 2015-08-27T14:04:55.840

Many other answers have code that uses timeouts for other things, so this should be fine too. – Solomon Ucko – 2017-12-23T20:03:58.237

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.

Beta Decay

Posted 2015-08-25T21:04:42.503

Reputation: 21 478

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

– hakr14 – 2018-04-03T16:49:06.637

2

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

Jacob Misirian

Posted 2015-08-25T21:04:42.503

Reputation: 737

Just checking, when was this language first created? – Beta Decay – 2015-10-02T16:48:27.443

August 9th 2015 – Jacob Misirian – 2015-10-03T17:40:24.050

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.

david

Posted 2015-08-25T21:04:42.503

Reputation: 479

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!

dana

Posted 2015-08-25T21:04:42.503

Reputation: 2 541

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

Kevin Cruijssen

Posted 2015-08-25T21:04:42.503

Reputation: 67 575

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.

12Me21

Posted 2015-08-25T21:04:42.503

Reputation: 6 110