sleep参数是整型还是小数

那些年踩过PHP的坑——sleep

一、背景

打算写一个专题,记录PHP踩过的坑,以sleep函数开篇。

二、函数说明

int sleep ( int $seconds )

程序延迟执行指定的 seconds 的秒数。
成功时返回 0,错误时返回 FALSE。

三、坑点

参数传入小数,例如程序中sleep(0.5)不能起到作用,因为0.5转化成整型为0。即sleep(0),所以不能起到延缓执行的作用。

四、解决方案

使用usleep函数

void usleep ( int $micro_seconds )

以指定的微秒数延缓程序的执行。例如延缓0.5秒执行,即usleep(500000)。
附官网手册下的一则评论:

This may seem obvious, but I thought I would save someone from something that just confused me: you cannot use sleep() to sleep for fractions of a second. This:

<?php sleep(0.25) ?>

will not work as expected. The 0.25 is cast to an integer, so this is equivalent to sleep(0). To sleep for a quarter of a second, use:

<?php usleep(250000) ?>
原文地址:https://www.cnblogs.com/qaing123/p/9406949.html