2 ** mrb_sleep - sleep methods for mruby
4 ** Copyright (c) mod_mruby developers 2012-
6 ** Permission is hereby granted, free of charge, to any person obtaining
7 ** a copy of this software and associated documentation files (the
8 ** "Software"), to deal in the Software without restriction, including
9 ** without limitation the rights to use, copy, modify, merge, publish,
10 ** distribute, sublicense, and/or sell copies of the Software, and to
11 ** permit persons to whom the Software is furnished to do so, subject to
12 ** the following conditions:
14 ** The above copyright notice and this permission notice shall be
15 ** included in all copies or substantial portions of the Software.
17 ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18 ** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19 ** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
20 ** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
21 ** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
22 ** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
23 ** SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25 ** [ MIT license: http://www.opensource.org/licenses/mit-license.php ]
31 #define sleep(x) Sleep(x * 1000)
32 #define usleep(x) Sleep((DWORD)((x)<1000) ? 1 : ((x)/1000))
40 /* not implemented forever sleep (called without an argument)*/
42 mrb_f_sleep(mrb_state *mrb, mrb_value self)
46 #ifndef MRB_WITHOUT_FLOAT
49 mrb_get_args(mrb, "f", &sec);
51 usleep(sec * 1000000);
54 mrb_raise(mrb, E_ARGUMENT_ERROR, "time interval must not be negative");
59 mrb_get_args(mrb, "i", &sec);
63 mrb_raise(mrb, E_ARGUMENT_ERROR, "time interval must not be negative");
68 return mrb_fixnum_value(end);
71 /* mruby special; needed for mruby without float numbers */
73 mrb_f_usleep(mrb_state *mrb, mrb_value self)
78 unsigned __int64 st_time = 0;
79 unsigned __int64 ed_time = 0;
81 struct timeval st_tm,ed_tm;
86 GetSystemTimeAsFileTime(&st_ft);
88 gettimeofday(&st_tm, NULL);
91 /* not implemented forever sleep (called without an argument)*/
92 mrb_get_args(mrb, "i", &usec);
97 mrb_raise(mrb, E_ARGUMENT_ERROR, "time interval must not be negative integer");
101 GetSystemTimeAsFileTime(&ed_ft);
103 st_time |= st_ft.dwHighDateTime;
105 st_time |= st_ft.dwLowDateTime;
106 ed_time |= ed_ft.dwHighDateTime;
108 ed_time |= ed_ft.dwLowDateTime;
110 slp_tm = (ed_time - st_time) / 10;
112 gettimeofday(&ed_tm, NULL);
114 if (st_tm.tv_usec > ed_tm.tv_usec) {
115 slp_tm = 1000000 + ed_tm.tv_usec - st_tm.tv_usec;
118 slp_tm = ed_tm.tv_usec - st_tm.tv_usec;
122 return mrb_fixnum_value(slp_tm);
126 mrb_mruby_sleep_gem_init(mrb_state *mrb)
128 mrb_define_method(mrb, mrb->kernel_module, "sleep", mrb_f_sleep, MRB_ARGS_REQ(1));
129 mrb_define_method(mrb, mrb->kernel_module, "usleep", mrb_f_usleep, MRB_ARGS_REQ(1));
133 mrb_mruby_sleep_gem_final(mrb_state *mrb)