立ち止まって、今いるところに立ちなさい!


35

チャレンジ

1つのパラメーター(整数)を受け取る関数を作成しますt。PythonやBBC BASICの場合とt同様にtime.sleep(t)、関数は続行する前にプログラムを数秒間停止する必要がありますWAIT t

特定の時間後にコードを実行するために、組み込みの待機関数または組み込み関数を使用しないでください。プログラムはt数秒後に再開する必要があります。

あなたの機能をテストするためtに、あなた自身のマシンで与えられたものよりも0.1秒の多かれ少なかれの許容差があります:コンピュータ間の違いは問題ありません。

誰かがあなたの答えに挑戦した場合、あなたの機能がt=1t=5およびで正しく機能することを写真(スクリーンショット)で証明する必要がありますt=25。また、コンピューターの詳細を提供して、他のユーザーが自分のコンピューターでそれを複製できるようにすることもできます。

プログラムは、クロック速度が1.6 GHz以上のコンピューターで実行する必要があります。

勝ち

最短のプログラムが勝ちます。

バウンティ

報奨金は、プログラムを停止する最短のプログラムに出て行くことなく、経過時間をチェックするループ使用します。あなたがこの賞金のために走っている場合、あなたの答えは賞金のためであると言っている脚注を追加してください。

リーダーボード

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


選択したプログラミング言語(咳咳)が1秒の精度までしか時間を取得できない場合はどうでしょうか?
ドアノブ

@Doorknob入力は整数なので、それで問題ありません
ベータ減衰

3
@Doorknobを使用すると、おそらくプログラムの外部で実行時間を測定できます。たとえば、デバッグ出力やDebugViewのタイムスタンプの確認などです。
トーマスウェラー

1
タイトルとBBC BASIC例はテレビ番組シャーロックへの参照ですか、これを読みすぎていますか?
15

1
まあ少なくともそれはあなたのタイトルが不正確だったことに気づきました;)
致命的

回答:


36

x86_64マシンコード、10バイト

コードのHexdump:

48 69 c9 ca fc 59 38 e2 fe c3

ソースコード(ml64Visual Studioでアセンブル可能):

    TITLE   heh

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

指定した値から0まで空のループを実行します。テストプログラムが満足のいく結果を出力するまで、試行錯誤により経験的に乗数945421514を選択しました。

テストプログラム(期間1、5、25秒ごとに10回待機):

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

結果:

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

このプログラムは、他に何もすることのないWindowsコンピューターで実行しました。いくつかのアプリケーションを実行する場合、待ち時間はより不安定になります。

CPU速度は3.9 GHzです。このコードは、現在のPCテクノロジーでほとんど十分でないようです。クロック周波数が約8.8 GHzの場合、乗算器は符号付き32ビット整数に適合しません。


PSこの回答では、どれだけ時間が経過したかはチェックされないため、賞金の候補となります。


4
これはクールです:D
ベータ崩壊

12
3900 GHz?わあ!たぶんMHz?
WayToDoor

2
@WayToDoor修正済み!また、それに関連する楽しい情報も追加しました。
アナトリグ

1
ソースは142バイトであるため、これがこの回答の得点です。
ピーターテイラー

3
@PeterTaylor アセンブリ言語の 142バイト。マシンコードでははるかに少ない。これらは異なる言語です。私の意見では、マシンコードはもっと楽しいです(ただし、[制限されたソース]の課題ではアセンブリ言語の方が良いでしょう)。マシンコードの問題は、非ASCIIであるということであり、大きな問題ではないと思います。関連する問題については、ここで説明します。私(またはあなた)はそこでマシンコードに関する議論を始めるべきですか?
アナトリグ

21

バッシュ、29 25 24 23 19バイト

w()(ping -t$1 1.2)

精度テスト(time)ここで$1= 1秒:

real    0m1.012s
user    0m0.001s
sys     0m0.002s

バイト数を23から19に削減したデニスに感謝します!

編集pingLinux ping 0.0.0.0(ループバックデバイス)で回避するためにIPを変更しました。


仕組み

ping デフォルトのタイムアウトは1秒であるため、存在しないIPアドレスに接続する場合、タイムアウトが経過するか、IPから応答があるまでpingを続行できません。

-t伝えpingしようとする$1強制的に、この偽のIPアドレスに回数をping取るため$1にpingを完了するために、秒。


賞金の対象です!ループなし!


ゴルフ:(w()(ping -t$1 0.0)pingのsが必要です。私は-w$1localhostを必要とし、ローカルホストから応答を受け取ります。)
デニス

そうです、OS Xでのみ動作する必要があります/dev/lo
-georgeunix

Linuxで0.0から1.2に変更
-georgeunix

OS Xではw 10、を10.02 sec real使用していtimeます。
ジョージユニックス

w()(ping -w$1 1.2)魅力のように機能します。
デニス

18

Matlab、33バイト

function f(t)
tic;while toc<t,end

または、Octaveでこれを使用することもできます。 ます。オンラインで試してください

Matlab、31バイト

以下のよう@flawrによって提案され、それは無名関数(それはそれを使用するために名前を割り当てる必要があります)を行うことができます。

@(t)eval('tic;while toc<t,end')

例:

>> 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
未割り当ての関数ハンドルも大丈夫な場合は、使用することもできます@(t)eval('tic;while toc<t,end')
-flawr

@flawrうわー!eval匿名関数にいくつかのステートメントをパックするために使用する非常に素晴らしいトリック。ありがとう!
ルイスメンドー

はい、それは時々役に立つトリックですが、eval内であっても変数に値を割り当てることはできません。私はまだ再帰関数の関数ハンドルを悪用する方法に取り組んでいます=)PS:関数ハンドルに名前を割り当てる必要は必ずしもありません。時には、ハンドルを別の関数の引数として直接渡すこともできますbsxfun
-flawr

+1。ただし、匿名関数バージョンはOctave(v 3.8.1)では機能しません。teval内の変数を認識できません。
pawel.boczarski

11

Java、63 62バイト

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

驚くべきことではありません-1970年1月1日以降のナノ秒数を複数回取得し、1秒が経過したかどうかを確認します。

Ypnypnとaditsuのおかげで1バイト節約されました。


25
わーい!100バイト以下のJavaプログラム; D
ベータ崩壊

5
@BetaDecayそれが実際にプログラムではないことを除いて。
user253751

1
誰かがあなたがforでそれを短縮できると言っていませんでしたか?for(long a=System.nanoTime();System.nanoTime()-a<t*1E9;);
aditsu

とは何t->ですか?
明るい

1
@Luminousこれは、Java 8で一般的に使用されるラムダ式です。
TNT

8

バッチ、27バイト

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

バッチにはスリープ機能がないため、一般的なバッチトリックです。

ループがないため、賞金の対象となります


ゴルフ:set/ac=%1+12バイト節約します。
stevefestl

7

コモドール64ベーシック、19 16バイト

1000 FORI=1TO930*N:NEXT:RETURN

電話で N=<number-of-secods>:GOSUB1000

ただし、十分な精度を提供することはできません。C64が約1 MHzのCPU速度を持っていたので、私は空にするためには良い十分だった覚えているFOR- NEXTそれがあったように、ループ1000倍を 1秒。

実際、マシンには2つの主要なバージョンがありました。PAL0.985 MHzとNTSC 1.023 MHz(C64ウィキペディアのページからのすべてのデータ)。NTSCバージョンがあるため、ループを約930回実行する必要がありました。

次のプログラムを使用してテストします(N秒、ユーザーがで提供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$は、hhmmss最後のリセットから経過した時間を含む文字列(形式)を含むシステム変数です(ただし、1秒の精度ですが、CPU速度にも依存します。同じクロックであるため、これはまったく関係ありません)。

enter image description here

オンラインC64エミュレーターhttp://codeazur.com.br/stuff/fc64_final/で作成したスクリーンショット。

このプログラム(行1000のみ)は、コードを入力する前(38908バイト)と後(38893 38889バイト)の両方でテストしたように、メモリで16 19バイトを占有します。PRINT FRE(0)+65535PRINT FRE(0)BASICプログラムの空きメモリを返します(負の値と定数です65535を追加する必要がありますが、実際には問題ではありません)。

このプログラムはループ内の経過時間をテストしないため、賞金の対象となります。


TI$変数がどのように正確であるかをテストしたのを覚えています。基準クロック(C64の外部)と2時間の差があるため、精度は十分です。私が確信していないのは値950ですが、それは他の値<1000(私は確信しています)でしょうか、それはまだ同じバイト量です
-Voitcus

J変数はテストプログラムの一部ではなく、何らかの形で実際のコードの一部である必要があると思います。したがって、変数は1秒だけでなくN秒待機します。しかし、それをBASICの構文に統合する方法がわかりません。
アナトリグ

@anatolygうーん、あなたは正しいです、それは1000 FOR I=1 TO N:FOR I=1 TO 950:NEXT I:NEXTJ:RETURN例えば電話のようなものであるべきです。200 N=5:GOSUB 1000。また、OPには関数が必要であることに気付きました。私はそれを修正しようとします
ヴォイトカス

@anatolyg修正しました-BASICには機能がないのでGOSUB- RETURNステートメントを使用しています
-Voitcus

@Voitcus DEF FNBBC BASIC でも好きではない?
ベータ崩壊

7

JavaScriptのES6、50の 45 40バイト

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

これは自己実行機能を使用していますが、なぜ機能しないのかはわかり+new Dateません。


使用法

これをSafari Nightlyでテストしましたが、Firefoxでも動作します。テスト済み:

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

括弧で囲むことで実行できます:

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

または、名前を付けて:

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

説明

プログラムの背後にある主なロジックは次のとおりです。

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

私が使用しているバージョンは同じロジックを使用しています:

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

これは、実行または変数に保存できるブロックです(つまり、名前付き関数になります)。デニスとコンセンサス氏は、ブロックだけを数えることは受け入れられることに同意します:)

説明:

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

オンラインで試す


1
Metaでのコンセンサスは、関数に名前を付ける必要がないということです。したがって、スタックに残っているブロックはラムダと同じように使用できると主張します。
デニス

6

JavaScript、68 54 51 42

スクリーンショットは必要ないと思います。しかし、私はあなたがこれをさらにもっとゴルフできると疑っています...

新しいバージョン:私はついに2回のnew使用を回避して使用することができましたDate

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

古いバージョン:

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
今はスクリーンショットは必要ありません:)このプログラムに誰かが挑戦した場合にのみ
ベータ崩壊

5

PHP、171 177 84 79 65 64 62バイト

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


使用法:次の
ように関数を呼び出します
php -d error_reporting=0 -r "require 'script.php'; a(5);echo 'Hello, World!';"
。5は、プログラムが「Hello、World!」をエコーするまで待機する時間(秒単位)です。


説明:
最初に、関数は現在の時刻をミリ秒単位で取得します。次に、関数は、現在のTimeが最初の時間+入力よりも小さくなるまでループを実行します。その後、「Hello World!」エコーされます。

ログ:
Voitcusのおかげで113バイトを節約axiacの
おかげで2バイトを節約


1
それは- マニュアル$get_as_floatパラメーターを参照してください。また削除$t$s-あなたは(私のコードを参照)、それらを必要としない
Voitcus

1
1e6 = 1000000 100万。echo 1e6;動作します。しかし、はい-フロートとして取得するのは秒数$e=microtime(1)+$i;なので、十分でしょう
-Voitcus

2
作業フィドルあなたのために
Voitcus

1
@Voitcus、ご協力ありがとうございます!
-jrenk

1
さらに2バイト(PHP 7では3バイト)節約できます:3v4l.org/fU11Y
axiac

5

ジュリア、33 20バイト

t->watch_file(".",t)

の関数シグネチャの変更により、Julia v0.4でのみ機能しますwatch_file。関数でtタイムアウトパラメータを使用する(ab)単一のパラメータを使用して、匿名関数を定義しwatch_fileます。

これは賞金の候補です!

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

以前の回答(33バイト)、ジュリア安定版でも動作

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

4

R、48バイト

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

デモンストレーション:

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
f=バイトカウントに含める必要はないと思います。関数スニペットは問題ありません。
ソロモンウッコ

4

PHP、39バイト

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

(コマンドラインで渡される引数を利用することにより、完全なプログラムが必要な場合、実際にこれを短くできることに注意してください。35まで

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

テストに使用したプログラム:

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

結果:

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

enter image description here


私は賞金の資格がありますが、他のエントリーのいくつかと一緒に走ることはほとんどありません!


はい、バイトカウントは問題ありません
ベータ崩壊

4

Windows CMD、22バイト

ping -w 1000 -n %1 1.1

これはループ(ラベルとgoto)を使用しないため、賞金の対象となります

tpingを1.0.0.1(無効)に送信し、1000ミリ秒の応答を待ちます


3

JavaScript ES6、40バイト

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

以下でテスト済み:

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

何を説明できますelapsed(STOP, t)か?STOPと経過とは何ですか?
ベータ崩壊

elapsedは、最初の引数を実行するのにかかった時間を測定します。この場合、STOPは、最初のコードスニペットです。経過する2番目の引数は、に渡される引数STOPです。
デンドロビウム

3

TI-BASIC(84 + SE)、21バイト

入力方法:T:prgmT。これは、TI-BASICの関数に最も近いものです。プログラム:

For(A,1,841Ans
End

すべての精度は試行錯誤によって得られます。ストップウォッチでタイミングを計ると、指定されたすべてのテストケースで20秒以内に機能します。

デバイス情報:

RAM FREE   23312
ARC FREE  889802


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

賞金の対象となるW00T!


1
ご存知でしたか:計算機のFor(ループの速度は、文字変数がいくつあるかによって異なりますか?より多くの変数がVATを詰まらせ、最大20%程度の時間を費やす可能性があります。システム変数(n、などXmin)は影響を受けません。
リトシアスト

わーい!面白い。ファイルを転送する時間があるときに、クリーンな計算機で再調整します。
コナーオブライエン

2

Python、57バイト

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

関数を呼び出す y()


2

PureBasic、92バイト

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

それは私が考えることができる最短です。ここでも最長になると思います...

テストする:

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

2

PowerShell、75バイト

長い説明的なプロシージャコール。言語をわかりやすくするために、いや。:)

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

次のようなものでプログラム内で呼び出されます

Get-Date
w(15)
Get-Date

または、代わりに外部プログラムの呼び出しが許可されている場合、次のようにすると59バイトになります。

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

これは、プログラム内で次のように呼び出されます(上記を「wait-function.ps1」として保存し、同じフォルダーに保存すると仮定します)。

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

ただし、関数/プログラムを作成する際に保存するものは、実際に実行するために必要な余剰分だけではありません。ため息。


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.

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.