Difference among sleep() and usleep() in PHP

柔情痞子 提交于 2019-11-30 21:43:52

问题


Can any body explain me what is the difference among sleep() and usleep() in 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);

page1.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

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

回答1:


The argument to sleep is seconds, the argument to usleep is microseconds. Other than that, I think they're identical.

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

usleep(25000) only sleeps for 0.025 seconds.




回答2:


sleep() allows your code to sleep in seconds.

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

usleep() allows your code with respect to microseconds.

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



回答3:


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

Is there any difference between the two?



回答4:


Simply

usleep uses CPU Cycles while sleep does not.

sleep takes seconds as argument

while usleep takes microseconds as argument




回答5:


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



来源:https://stackoverflow.com/questions/19557642/difference-among-sleep-and-usleep-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!