如何在swift 2.2中睡眠几毫秒?

如何在swift 2.2中睡眠几毫秒?,swift,uikit,sleep,Swift,Uikit,Sleep,请告诉我如何在swift 2.2中使用sleep()几毫秒 while (true){ print("sleep for 0.002 seconds.") sleep(0.002) // not working } 但是 它正在工作。使用func-usleep(\uuuu:useconds\u t)->Int32(导入Darwin或Foundation…)如果你真的需要睡觉,按照@user3441734的回答尝试usleep 然而,你可能想考虑睡眠是否是最好的选择:它就像一个暂

请告诉我如何在swift 2.2中使用sleep()几毫秒

while (true){
    print("sleep for 0.002 seconds.")
    sleep(0.002) // not working
}
但是


它正在工作。

使用
func-usleep(\uuuu:useconds\u t)->Int32
(导入
Darwin
Foundation
…)

如果你真的需要睡觉,按照@user3441734的回答尝试
usleep

然而,你可能想考虑睡眠是否是最好的选择:它就像一个暂停按钮,应用程序在运行时会被冻结和反应迟钝。 您可能希望使用

NSTimer

 //Declare the timer
 var timer = NSTimer.scheduledTimerWithTimeInterval(0.002, target: self, selector: #selector(MyClass.update), userInfo: nil, repeats: true)
 self, selector: "update", userInfo: nil, repeats: true)



func update() {
    // Code here
}
usleep()需要百万分之一秒的时间

usleep(1000000) //will sleep for 1 second
usleep(2000) //will sleep for .002 seconds

或者: usleep的非阻塞解决方案:
我认为在当前的swift语法中,比usleep更优雅的解决方案是:
Thread.sleep(forTimeInterval:0.002)

有时候,将一些后台任务“暂停”一段时间是个好主意。。。而sleep和usleep可能是非常有用的、易于采用且价格低廉的解决方案。不幸的是,很少看到睡眠或usleep的正确使用。一般来说,最好避免:-)只有暂停事件线程时才会冻结应用程序,这总是一个糟糕的想法。用户界面以外的工作无论如何都应该在该线程之外完成。正常使用usleep只会导致当前线程阻塞。呃,如果你在应用程序的高级部分调用
usleep
,这很可能是一个坏兆头。例如,它可以阻止GCD队列。只有在苹果提供的抽象确实不适合您需要做的事情时才使用。例如,线程睡眠或产量在轮询的情况下是有效的。许多接口不提供通知,因此您必须经常检查即将发生的异步更改。在检查之间不暂停线程的情况下执行此操作将不必要地干扰CPU,并且可能会阻塞您正在等待的进程。sleep()将int作为参数。因此,睡眠(0.002)将睡眠0秒。使用usleep(纳秒)代替teadusleep()需要百万分之一秒,因此usleep(1000000)将睡眠1秒32(0.002)为0。它应该是
usleep(UInt32(0.002*second))
我没有深入了解它是如何工作的,但在objective-C(和Swift)中,这段代码似乎在不破坏以前的线程的情况下,每个
dTime
生成一个新线程。所以,在更好的情况下,您会浪费设备的内存,在最坏的情况下,应用程序会因为巨大的内存消耗而崩溃(取决于循环计数)
usleep(1000000) //will sleep for 1 second
usleep(2000) //will sleep for .002 seconds
 let ms = 1000
 usleep(useconds_t(2 * ms)) //will sleep for 2 milliseconds (.002 seconds)
let second: Double = 1000000
usleep(useconds_t(0.002 * second)) //will sleep for 2 milliseconds (.002 seconds)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.002) {
   /*Do something after 0.002 seconds have passed*/
}
DispatchQueue.global(qos: .background).async {
    let second: Double = 1000000
    usleep(useconds_t(0.002 * second)) 
    print("Active after 0.002 sec, and doesn't block main")
    DispatchQueue.main.async{
        //do stuff in the main thread here
    }
}