--Written by Ryan Johnson --Date: 2007-06-10 --http://fluidae.com/ --You make use this code freely. --Currently runs only on linux and windows. --Euphoria 3.0.0 or higher required for the idletask() procedure. --If you have an older version, you can still use nanosleep() if you comment out idletask() include machine.e include misc.e include dll.e atom syslib, func_nanosleep if platform() = WIN32 then syslib = open_dll("Kernel32.dll") func_nanosleep = define_c_proc(syslib, "Sleep", {C_UINT}) --NOTE: resolution is only to 1 millisecond on Windows elsif platform() = LINUX then syslib = open_dll("") func_nanosleep = define_c_func(syslib, "nanosleep", {C_POINTER, C_POINTER}, C_INT) elsif platform() = DOS32 then end if global procedure nanosleep(atom s) --Sleeps for s seconds. 0.000000001 s = 1 nanosecond. --This is compatible with the sleep() function. However, you can use non-integers as well. --For example: -- nanosleep(0.001) --sleeps for 1 millisecond -- nanosleep(0.000000001) --this is the smallest amount of time possible (linux) -- nanosleep(0) --sleeps for the smallest amount of time possible -- nanosleep(1.5) -- nanosleep(17.0003) -- nanosleep(0.5) -- --Note: It is normal for the program to sleep for slightly more than the specified time, due --to multitasking scheduling. --Also, on windows, the resolution seems to be only milliseconds, not nanoseconds. atom void, p_s if platform() = WIN32 then --p_s = allocate(2) --poke4(p_s + 0, (s - floor(s)) * 1000) --void = c_func(func_nanosleep, {p_s}) c_proc(func_nanosleep, {(s - floor(s)) * 1000}) elsif platform() = LINUX then p_s = allocate(8) poke4(p_s + 0, floor(s)) poke4(p_s + 4, (s - floor(s)) * 1000000000) void = c_func(func_nanosleep, {p_s, 0}) end if end procedure global procedure delay(atom delaytime) --causes a delay while allowing other tasks to run. atom t t = time() while time() - t < delaytime do nanosleep(0.01) task_yield() end while end procedure global procedure idletask(atom idletime) --allows the new Euphoria task manager to idle the cpu when other tasks are not scheduled to run. --without this, a Euphoria program will use 100% cpu when there is less than 1 second between --scheduled tasks! -- --To use this properly, insert the following code into your program: -- -- atom task_idle -- task_idle = task_create(routine_id("idletask"), {0.001}) -- task_schedule(task_idle, 1) -- --The task will be scheduled to run whenever real-time tasks are not running. It should not --affect the performance of the application. --If you want to, you can experiment with different values for idletime.If you try 0 seconds --on windows, you program may still use 100% CPU. I would recomment trying 0.001 seconds first. while 1 do nanosleep(idletime) task_yield() end while end procedure