답변
usleep
때문에, 당신은
import time
time.sleep(seconds/1000000.0)
time.sleep()
매개 변수로 초가 소요 1000000하여 초 값을 분할한다.
from time import sleep
sleep(seconds)
More info. 일반적으로는 X의 마이크로의 실행을 지연 시킨다는 것을 의미
from time import sleep
sleep(0.1) #sleep during 100ms
import time
usleep = lambda x: time.sleep(x/1000000.0)
usleep(100) #sleep during 100μs
time.sleep 매우 매우주의해야합니다. 나는 그것이 비 단조이기 때문에 time.sleep을 사용하여 python3에 의해 불 태워진다. 벽시계가 뒤로 바뀌면, 잠자기 시간이 계획대로 진행 되었다면 벽시계가 멈출 때까지 time.sleep 콜은 끝나지 않습니다. 나는 아직 파이썬을위한 단조로운 차단 된 수면을 발견하지 못했다.
대신,이 같은 Event.wait 추천 :
이 방법에 대해def call_repeatedly(interval, func, *args, **kwargs):
stopped = Event()
def loop():
while not stopped.wait(interval): # the first call is in `interval` secs
try:
func(*args)
except Exception as e:
logger.error(e);
if kwargs.get('exception'):
kwargs.get('exception')(e) # SEND exception to the specified function if there is one.
else:
raise Exception(e)
Thread(target=loop).start()
return stopped.set
코드를 추가 하시겠습니까? 물론 – manetsus
, 내가 그러고 싶어 : [http://pastebin.com/0rZdY8gB] (http://pastebin.com/0rZdY8gB) – SynaTree
나는'time.sleep' 지금 파이썬 3에서 단순해야한다 믿는다 적어도, [소스 코드] (https://github.com/python/cpython/blob/v3.6.3/Modules/timemodule.c#L1430)에는'_PyTime_GetMonotonicClock()'이 나와 현재 시간을 알 수 있습니다. 나는 과거의 행동이 어떤 것인지 확실히 말할 수 없다. – user2357112
:
import time
def usleep(delay):
mdelay = delay /1000
now = time.time()
while now + mdelay > time.time():
pass
지연이 끝날 때까지 100 % CPU를 소비합니까? 이것은 개발자가 MSDOS 시절에 한 일입니다. 현대의 멀티 태스킹 시스템에서는 이것을하지 마십시오. 'time.sleep()'을 사용하면 타임 아웃이 끝날 때까지 OS 커널이 일시 중지 상태가되도록 지시하므로 다른 모든 프로세스가 대신 작업을 수행 할 수 있습니다. – vdboor
이것은 CPU의 100 %를 소비 할 수도 있지만 적어도 적어도 수면보다 정확합니다. 타이밍을 유지하기 위해 수면을 많이 취해야하는 경우 (예 : Rapsberry Pi time.sleep()의 프로토콜을 bitbanging 할 때 가끔은 (나는 factor 20에 대해 이야기하고있다.) – Dakkaron
clocksource가 시스템로드 및 드롭의 영향을받는다면 CPU를 100 %로드하여 실제로 시계를 느리게 할 수있다. 전압의 ... 당신이 그런 식으로 자고있는 정밀도를 잃을 뿐이라는 것을 명심하십시오. – Andrew
파이썬위한 또 다른 절전 기능.
참고 : GIL 잠금으로 인해 여러 스레드에 사용하지 말고 여러 개의 하위 프로세스를 사용하는 것이 좋습니다. time.sleep()과 같습니다.
파이썬에 C 함수를 래핑합니다. C 라이브러리의 nanosleep()을 사용하고 있습니다.이 라이브러리는 많은 시간 동안 실행되는 스레드를 정지시킵니다. 그것은 많은 CPU를 사용하여 수학을 평가하는 바쁜 대기 유형의 지연이 아닙니다. 코드는 다음과 같습니다. 모든 것을 폴더에 넣어 라.
C_functions.h
#include <time.h>
int c_sleep_msec(long milliseconds);
int c_sleep_nsec(long nanoseconds);
C_functions.c
#include "C_functions.h"
int c_sleep_msec(long milliseconds) {
struct timespec req;
//struct timespec rem;
if(milliseconds > 999) {
req.tv_sec = (int)(milliseconds/1000); /* Must be Non-Negative */
req.tv_nsec = (milliseconds - ((long)req.tv_sec * 1000)) * 1000000; /* Must be in range of 0 to 999999999 */
}
else {
req.tv_sec = 0; /* Must be Non-Negative */
req.tv_nsec = milliseconds * 1000000; /* Must be in range of 0 to 999999999 */
}
//rem = NULL;
return nanosleep(&req , NULL);
}
//------------------------------------------------------
int c_sleep_nsec(long nanoseconds) {
struct timespec req;
//struct timespec rem;
if (nanoseconds > 999999999) {
req.tv_sec = (int)(nanoseconds/1000000000);
req.tv_nsec = (nanoseconds - ((long)req.tv_sec * 1000000000));
}
else {
req.tv_sec = 0;
req.tv_nsec = nanoseconds;
}
//rem = NULL;
return nanosleep(&req , NULL);
}
또한 동일한 인 nanosleep()
CWrapper.pyx
cdef extern from "C_functions.h":
int c_sleep_msec(long milliseconds)
int c_sleep_nsec(long nanoseconds)
def sleep_msec(milliseconds):
return c_sleep_msec(milliseconds)
def sleep_nsec(nanoseconds):
return c_sleep_nsec(nanoseconds)
을 이용한 마이크로 초 함수를 생성 할
setup.py
from distutils.core import setup
from distutils.extension import Extension
from Pyrex.Distutils import build_ext
setup(
name = "CWrapper",
ext_modules=[ Extension("CWrapper", ["CWrapper.pyx", "C_functions.c"]) ],
cmdclass = {'build_ext': build_ext}
)
python-pyrex를 설치하십시오. 그런 다음 리눅스 터미널에서 실행하십시오.
python setup.py build_ext -i
CWrapper.c, build 및 CWrapper.so 파일이 생성됩니다. 어느 곳에서나 CWrapper.so를 사용하고 파이썬으로 가져 오기 만하면됩니다.
참고 : Raspberry Pi에 대해 별도로 컴파일하십시오.
지금,
import serial
from multiprocessing import Process
import time
import CWrapper
class TestSleep:
def __init__(self):
self.delay_sec = 0.00000100
self.delay_msec = 30
self.delay_nsec = 1000 #200000000
self.start_time = time.time()
self.process_1 = Process(name="process_1", target=self.process_1_task, args=("process_1",))
self.process_1.daemon = True
self.process_1.start()
self.process_2 = Process(name="process_2", target=self.process_1_task, args=("process_2",))
self.process_2.daemon = True
self.process_2.start()
self.process_3 = Process(name="process_3", target=self.process_1_task, args=("process_3",))
self.process_3.daemon = True
self.process_3.start()
def process_1_task(self, process_name):
start = self.start_time
delay_msec = self.delay_msec
delay_sec = self.delay_sec
delay_nsec = self.delay_nsec
t1 = start
for i in range(1, 81):
status = CWrapper.sleep_msec(delay_msec)
# status = CWrapper.sleep_nsec(delay_nsec)
#status = time.sleep(delay_sec)
t2 = time.time()
elapsed_time = t2 - t1
t1 = t2
print process_name, i, "status:", status, "Elapsed-time:", elapsed_time
if __name__ == '__main__':
test = TestSleep()
# for i in range(1,10000):
# print "main thread", i
# time.sleep(0.1)
while True: # Since daemon=True, main thread should check join() or stay in loop
pass
는 파라미터 time.sleep위한 delay_sec 바리 함수
에게 Test_sleep.py
테스트() CWrapper.sleep_msec()에 대한 delay_msec, CWrapper.sleep_nsec위한 delay_nsec(). thread_1_task()에서 테스트 할 함수의 주석 처리를 제거하십시오.이것이이 지위를 복사 한 곳입니까? 귀하의 예는 여전히 스레드를 혼란스럽게하고 있습니다 (회전 속도가 빠르며 실행되지 못함). 따라서 비교가되지 않습니다. 인식 된 문제를 다룰 때 "부적절한"것보다 더 잘 정의하십시오. –
당신의 증거에 관해서는, 그것이 바쁜 기다리는자는 아니지만 그것은 여전히 당신의 주된 스레드입니다; 당신이 작성한 루틴은 모든 * 파이썬 스레드를 막 중지시킵니다. –
내 응용 프로그램의 필요가 각 스레드 –
- 1. 주기 여기 usleep
- 2. Regex in Python
- 3. Symlink Exploits in Python
- 4. SQLite in Python 2.2.3
- 5. binary16 in Python
- 6. 정확한 trig in python
- 7. webapp in python
- 8. Generics/templates in python?
- 9. dictionary in django python
- 10. org.apache.commons.lang.StringEscapeUtils in python
- 11. Delaunay tessellation in Python?
- 12. Yahoo Chat in Python
- 13. Mutex in Python Twisted
- 14. __rlshift__, __ror__ in Python
- 15. MongoDB gui in python
- 16. Vix API in python
- 17. Flash in Python
- 18. sqlite3 in Python
- 19. SCons in Python
- 20. TDD in python 3.1
- 21. import statement in python
- 22. MySQL in Python 2.5
- 23. Speex in Python
- 24. URL Sniffing in Python
- 25. bytearray in Python
- 26. Jena TDB in Python?
- 27. subprocess.Popen call in Python
- 28. Session in python?
- 29. usleep()을 사용하여 스로틀 cURL
- 30. 부동 소수점 수와 usleep 문제
주의 : [sleep()의 정확성] (http://stackoverflow.com/questions/1133857/how-accurate-is-pythons-time-sleep)을 읽어보십시오. – x29a