PHP 中 sleep() 和 usleep() 的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19557642/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 19:41:36  来源:igfitidea点击:

Difference among sleep() and usleep() in PHP

phpsleepusleep

提问by MaxEcho

Can any body explain me what is the difference among sleep()and usleep()in PHP.

任何机构都可以向我解释PHPsleep()usleep()PHP之间的区别。

I have directed to use following scripts to do chat application for long pulling but in this script I am getting same effect using usleep(25000);or without usleep(25000);

我已指示使用以下脚本来进行长时间拉动的聊天应用程序,但在此脚本中,usleep(25000);无论是否使用,我都获得了相同的效果usleep(25000);

page1.php

页面1.php

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" 
       type="text/javascript"></script>

<script>
var lpOnComplete = function(response) {
    console.log(response);
    // do more processing
    lpStart();
};

var lpStart = function() {
    $.post('page2.php', {}, lpOnComplete, 'json');
};

$(document).ready(lpStart);
</script>

page2.php

页面2.php

<?php
$time = time();
while((time() - $time) < 30) {
    // query memcache, database, etc. for new data
    $data = getLatest();

    // if we have new data return it
    if(!empty($data)) {
        echo json_encode($data);
        break;
    }

    usleep(25000);
}

function getLatest() {
    sleep(2);
    return "Test Data"; 
}
?>

回答by Barmar

The argument to sleepis seconds, the argument to usleepis microseconds. Other than that, I think they're identical.

的参数sleep是秒,参数usleep是微秒。除此之外,我认为它们是相同的。

sleep($n) == usleep($n * 1000000)

usleep(25000)only sleeps for 0.025 seconds.

usleep(25000)只休眠 0.025 秒。

回答by Ashwin

sleep()allows your code to sleep in seconds.

sleep()允许您的代码在几秒钟内休眠。

  • sleep(5); // sleeps for 5 seconds
  • sleep(5); // sleeps for 5 seconds

usleep()allows your code with respect to microseconds.

usleep()允许您的代码相对于微秒。

  • usleep(2500000); // sleeps for 2.5 seconds
  • usleep(2500000); // sleeps for 2.5 seconds

回答by shahpranaf

usleep()is used to delay execution in "microseconds" while sleep()is used to delay execution in seconds. So usleep(25000)is 0.025 seconds.

usleep()用于以“微秒”sleep()为单位延迟执行,而用于以秒为单位延迟执行。usleep(25000)0.025 秒也是如此。

Is there any difference between the two?

回答by qualia

One other difference is sleep returns 0 on success, false on error. usleep doesn't return anything.

另一个区别是 sleep 成功时返回 0,错误时返回 false。usleep 不返回任何东西。

回答by Matee Gojra

Simply

简单地

usleepuses CPU Cycleswhile sleepdoes not.

usleep使用CPU Cyclessleep没有。

sleeptakes secondsas argument

sleep需要seconds作为参数

while usleeptakes microsecondsas argument

同时usleep需要microseconds作为参数