9 #if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_FTIME)
11 * floattime falls back to ftime when getttimeofday fails because the latter
12 * might fail on some platforms. This fallback is unwanted on MacOSX because
13 * that makes it impossible to use a binary build on OSX 10.4 on earlier
14 * releases of the OS. Therefore claim we don't support ftime.
22 #ifdef HAVE_SYS_TYPES_H
23 #include <sys/types.h>
24 #endif /* HAVE_SYS_TYPES_H */
31 #include <sys/timeb.h>
32 #if !defined(MS_WINDOWS) && !defined(PYOS_OS2)
33 extern int ftime(struct timeb
*);
34 #endif /* MS_WINDOWS */
35 #endif /* HAVE_FTIME */
37 #if defined(__WATCOMC__) && !defined(__QNX__)
41 #define WIN32_LEAN_AND_MEAN
45 /* helper to allow us to interrupt sleep() on Windows*/
46 static HANDLE hInterruptEvent
= NULL
;
47 static BOOL WINAPI
PyCtrlHandler(DWORD dwCtrlType
)
49 SetEvent(hInterruptEvent
);
50 /* allow other default handlers to be called.
51 Default Python handler will setup the
52 KeyboardInterrupt exception.
56 static long main_thread
;
59 #if defined(__BORLANDC__)
60 /* These overrides not needed for Win32 */
61 #define timezone _timezone
62 #define tzname _tzname
63 #define daylight _daylight
64 #endif /* __BORLANDC__ */
65 #endif /* MS_WINDOWS */
66 #endif /* !__WATCOMC__ || __QNX__ */
68 #if defined(MS_WINDOWS) && !defined(__BORLANDC__)
69 /* Win32 has better clock replacement; we have our own version below. */
71 #endif /* MS_WINDOWS && !defined(__BORLANDC__) */
79 #if defined(PYCC_VACPP)
85 /* For bigtime_t, snooze(). - [cjh] */
86 #include <support/SupportDefs.h>
87 #include <kernel/OS.h>
91 extern int riscos_sleep(double);
94 /* Forward declarations */
95 static int floatsleep(double);
96 static double floattime(void);
99 static PyObject
*moddict
;
101 /* Exposed in timefuncs.h. */
103 _PyTime_DoubleToTimet(double x
)
109 /* How much info did we lose? time_t may be an integral or
110 * floating type, and we don't know which. If it's integral,
111 * we don't know whether C truncates, rounds, returns the floor,
112 * etc. If we lost a second or more, the C rounding is
113 * unreasonable, or the input just doesn't fit in a time_t;
114 * call it an error regardless. Note that the original cast to
115 * time_t can cause a C error too, but nothing we can do to
118 diff
= x
- (double)result
;
119 if (diff
<= -1.0 || diff
>= 1.0) {
120 PyErr_SetString(PyExc_ValueError
,
121 "timestamp out of range for platform time_t");
128 time_time(PyObject
*self
, PyObject
*unused
)
133 PyErr_SetFromErrno(PyExc_IOError
);
136 return PyFloat_FromDouble(secs
);
139 PyDoc_STRVAR(time_doc
,
140 "time() -> floating point number\n\
142 Return the current time in seconds since the Epoch.\n\
143 Fractions of a second may be present if the system clock provides them.");
147 #ifndef CLOCKS_PER_SEC
149 #define CLOCKS_PER_SEC CLK_TCK
151 #define CLOCKS_PER_SEC 1000000
156 time_clock(PyObject
*self
, PyObject
*unused
)
158 return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC
);
160 #endif /* HAVE_CLOCK */
162 #if defined(MS_WINDOWS) && !defined(__BORLANDC__)
163 /* Due to Mark Hammond and Tim Peters */
165 time_clock(PyObject
*self
, PyObject
*unused
)
167 static LARGE_INTEGER ctrStart
;
168 static double divisor
= 0.0;
172 if (divisor
== 0.0) {
174 QueryPerformanceCounter(&ctrStart
);
175 if (!QueryPerformanceFrequency(&freq
) || freq
.QuadPart
== 0) {
176 /* Unlikely to happen - this works on all intel
177 machines at least! Revert to clock() */
178 return PyFloat_FromDouble(((double)clock()) /
181 divisor
= (double)freq
.QuadPart
;
183 QueryPerformanceCounter(&now
);
184 diff
= (double)(now
.QuadPart
- ctrStart
.QuadPart
);
185 return PyFloat_FromDouble(diff
/ divisor
);
188 #define HAVE_CLOCK /* So it gets included in the methods */
189 #endif /* MS_WINDOWS && !defined(__BORLANDC__) */
192 PyDoc_STRVAR(clock_doc
,
193 "clock() -> floating point number\n\
195 Return the CPU time or real time since the start of the process or since\n\
196 the first call to clock(). This has as much precision as the system\n\
201 time_sleep(PyObject
*self
, PyObject
*args
)
204 if (!PyArg_ParseTuple(args
, "d:sleep", &secs
))
206 if (floatsleep(secs
) != 0)
212 PyDoc_STRVAR(sleep_doc
,
215 Delay execution for a given number of seconds. The argument may be\n\
216 a floating point number for subsecond precision.");
218 static PyStructSequence_Field struct_time_type_fields
[] = {
231 static PyStructSequence_Desc struct_time_type_desc
= {
234 struct_time_type_fields
,
238 static int initialized
;
239 static PyTypeObject StructTimeType
;
242 tmtotuple(struct tm
*p
)
244 PyObject
*v
= PyStructSequence_New(&StructTimeType
);
248 #define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyInt_FromLong((long) val))
250 SET(0, p
->tm_year
+ 1900);
251 SET(1, p
->tm_mon
+ 1); /* Want January == 1 */
256 SET(6, (p
->tm_wday
+ 6) % 7); /* Want Monday == 0 */
257 SET(7, p
->tm_yday
+ 1); /* Want January, 1 == 1 */
260 if (PyErr_Occurred()) {
269 time_convert(double when
, struct tm
* (*function
)(const time_t *))
272 time_t whent
= _PyTime_DoubleToTimet(when
);
274 if (whent
== (time_t)-1 && PyErr_Occurred())
277 p
= function(&whent
);
283 return PyErr_SetFromErrno(PyExc_ValueError
);
288 /* Parse arg tuple that can contain an optional float-or-None value;
289 format needs to be "|O:name".
290 Returns non-zero on success (parallels PyArg_ParseTuple).
293 parse_time_double_args(PyObject
*args
, char *format
, double *pwhen
)
297 if (!PyArg_ParseTuple(args
, format
, &ot
))
299 if (ot
== NULL
|| ot
== Py_None
)
300 *pwhen
= floattime();
302 double when
= PyFloat_AsDouble(ot
);
303 if (PyErr_Occurred())
311 time_gmtime(PyObject
*self
, PyObject
*args
)
314 if (!parse_time_double_args(args
, "|O:gmtime", &when
))
316 return time_convert(when
, gmtime
);
319 PyDoc_STRVAR(gmtime_doc
,
320 "gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,\n\
321 tm_sec, tm_wday, tm_yday, tm_isdst)\n\
323 Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
324 GMT). When 'seconds' is not passed in, convert the current time instead.");
327 time_localtime(PyObject
*self
, PyObject
*args
)
330 if (!parse_time_double_args(args
, "|O:localtime", &when
))
332 return time_convert(when
, localtime
);
335 PyDoc_STRVAR(localtime_doc
,
336 "localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\
337 tm_sec,tm_wday,tm_yday,tm_isdst)\n\
339 Convert seconds since the Epoch to a time tuple expressing local time.\n\
340 When 'seconds' is not passed in, convert the current time instead.");
343 gettmarg(PyObject
*args
, struct tm
*p
)
346 memset((void *) p
, '\0', sizeof(struct tm
));
348 if (!PyArg_Parse(args
, "(iiiiiiiii)",
360 PyObject
*accept
= PyDict_GetItemString(moddict
,
362 if (accept
== NULL
|| !PyInt_Check(accept
) ||
363 PyInt_AsLong(accept
) == 0) {
364 PyErr_SetString(PyExc_ValueError
,
365 "year >= 1900 required");
368 if (69 <= y
&& y
<= 99)
370 else if (0 <= y
&& y
<= 68)
373 PyErr_SetString(PyExc_ValueError
,
374 "year out of range");
378 p
->tm_year
= y
- 1900;
380 p
->tm_wday
= (p
->tm_wday
+ 1) % 7;
387 time_strftime(PyObject
*self
, PyObject
*args
)
389 PyObject
*tup
= NULL
;
392 size_t fmtlen
, buflen
;
396 memset((void *) &buf
, '\0', sizeof(buf
));
398 if (!PyArg_ParseTuple(args
, "s|O:strftime", &fmt
, &tup
))
402 time_t tt
= time(NULL
);
403 buf
= *localtime(&tt
);
404 } else if (!gettmarg(tup
, &buf
))
407 /* Checks added to make sure strftime() does not crash Python by
408 indexing blindly into some array for a textual representation
409 by some bad index (fixes bug #897625).
411 Also support values of zero from Python code for arguments in which
412 that is out of range by forcing that value to the lowest value that
413 is valid (fixed bug #1520914).
415 Valid ranges based on what is allowed in struct tm:
417 - tm_year: [0, max(int)] (1)
418 - tm_mon: [0, 11] (2)
423 - tm_wday: [0, 6] (1)
424 - tm_yday: [0, 365] (2)
425 - tm_isdst: [-max(int), max(int)]
427 (1) gettmarg() handles bounds-checking.
428 (2) Python's acceptable range is one greater than the range in C,
429 thus need to check against automatic decrement by gettmarg().
431 if (buf
.tm_mon
== -1)
433 else if (buf
.tm_mon
< 0 || buf
.tm_mon
> 11) {
434 PyErr_SetString(PyExc_ValueError
, "month out of range");
437 if (buf
.tm_mday
== 0)
439 else if (buf
.tm_mday
< 0 || buf
.tm_mday
> 31) {
440 PyErr_SetString(PyExc_ValueError
, "day of month out of range");
443 if (buf
.tm_hour
< 0 || buf
.tm_hour
> 23) {
444 PyErr_SetString(PyExc_ValueError
, "hour out of range");
447 if (buf
.tm_min
< 0 || buf
.tm_min
> 59) {
448 PyErr_SetString(PyExc_ValueError
, "minute out of range");
451 if (buf
.tm_sec
< 0 || buf
.tm_sec
> 61) {
452 PyErr_SetString(PyExc_ValueError
, "seconds out of range");
455 /* tm_wday does not need checking of its upper-bound since taking
456 ``% 7`` in gettmarg() automatically restricts the range. */
457 if (buf
.tm_wday
< 0) {
458 PyErr_SetString(PyExc_ValueError
, "day of week out of range");
461 if (buf
.tm_yday
== -1)
463 else if (buf
.tm_yday
< 0 || buf
.tm_yday
> 365) {
464 PyErr_SetString(PyExc_ValueError
, "day of year out of range");
467 if (buf
.tm_isdst
< -1 || buf
.tm_isdst
> 1) {
468 PyErr_SetString(PyExc_ValueError
,
469 "daylight savings flag out of range");
473 fmtlen
= strlen(fmt
);
475 /* I hate these functions that presume you know how big the output
476 * will be ahead of time...
478 for (i
= 1024; ; i
+= i
) {
479 outbuf
= (char *)malloc(i
);
480 if (outbuf
== NULL
) {
481 return PyErr_NoMemory();
483 buflen
= strftime(outbuf
, i
, fmt
, &buf
);
484 if (buflen
> 0 || i
>= 256 * fmtlen
) {
485 /* If the buffer is 256 times as long as the format,
486 it's probably not failing for lack of room!
487 More likely, the format yields an empty result,
488 e.g. an empty format, or %Z when the timezone
491 ret
= PyString_FromStringAndSize(outbuf
, buflen
);
496 #if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
497 /* VisualStudio .NET 2005 does this properly */
498 if (buflen
== 0 && errno
== EINVAL
) {
499 PyErr_SetString(PyExc_ValueError
, "Invalid format string");
507 PyDoc_STRVAR(strftime_doc
,
508 "strftime(format[, tuple]) -> string\n\
510 Convert a time tuple to a string according to a format specification.\n\
511 See the library reference manual for formatting codes. When the time tuple\n\
512 is not present, current time as returned by localtime() is used.");
513 #endif /* HAVE_STRFTIME */
516 time_strptime(PyObject
*self
, PyObject
*args
)
518 PyObject
*strptime_module
= PyImport_ImportModuleNoBlock("_strptime");
519 PyObject
*strptime_result
;
521 if (!strptime_module
)
523 strptime_result
= PyObject_CallMethod(strptime_module
, "_strptime_time", "O", args
);
524 Py_DECREF(strptime_module
);
525 return strptime_result
;
528 PyDoc_STRVAR(strptime_doc
,
529 "strptime(string, format) -> struct_time\n\
531 Parse a string to a time tuple according to a format specification.\n\
532 See the library reference manual for formatting codes (same as strftime()).");
536 time_asctime(PyObject
*self
, PyObject
*args
)
538 PyObject
*tup
= NULL
;
541 if (!PyArg_UnpackTuple(args
, "asctime", 0, 1, &tup
))
544 time_t tt
= time(NULL
);
545 buf
= *localtime(&tt
);
546 } else if (!gettmarg(tup
, &buf
))
551 return PyString_FromString(p
);
554 PyDoc_STRVAR(asctime_doc
,
555 "asctime([tuple]) -> string\n\
557 Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
558 When the time tuple is not present, current time as returned by localtime()\n\
562 time_ctime(PyObject
*self
, PyObject
*args
)
568 if (!PyArg_UnpackTuple(args
, "ctime", 0, 1, &ot
))
570 if (ot
== NULL
|| ot
== Py_None
)
573 double dt
= PyFloat_AsDouble(ot
);
574 if (PyErr_Occurred())
576 tt
= _PyTime_DoubleToTimet(dt
);
577 if (tt
== (time_t)-1 && PyErr_Occurred())
582 PyErr_SetString(PyExc_ValueError
, "unconvertible time");
587 return PyString_FromString(p
);
590 PyDoc_STRVAR(ctime_doc
,
591 "ctime(seconds) -> string\n\
593 Convert a time in seconds since the Epoch to a string in local time.\n\
594 This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
595 not present, current time as returned by localtime() is used.");
599 time_mktime(PyObject
*self
, PyObject
*tup
)
604 buf
= *localtime(&tt
);
605 if (!gettmarg(tup
, &buf
))
608 if (tt
== (time_t)(-1)) {
609 PyErr_SetString(PyExc_OverflowError
,
610 "mktime argument out of range");
613 return PyFloat_FromDouble((double)tt
);
616 PyDoc_STRVAR(mktime_doc
,
617 "mktime(tuple) -> floating point number\n\
619 Convert a time tuple in local time to seconds since the Epoch.");
620 #endif /* HAVE_MKTIME */
622 #ifdef HAVE_WORKING_TZSET
623 static void inittimezone(PyObject
*module
);
626 time_tzset(PyObject
*self
, PyObject
*unused
)
630 m
= PyImport_ImportModuleNoBlock("time");
637 /* Reset timezone, altzone, daylight and tzname */
645 PyDoc_STRVAR(tzset_doc
,
648 Initialize, or reinitialize, the local timezone to the value stored in\n\
649 os.environ['TZ']. The TZ environment variable should be specified in\n\
650 standard Unix timezone format as documented in the tzset man page\n\
651 (eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
652 fall back to UTC. If the TZ environment variable is not set, the local\n\
653 timezone is set to the systems best guess of wallclock time.\n\
654 Changing the TZ environment variable without calling tzset *may* change\n\
655 the local timezone used by methods such as localtime, but this behaviour\n\
656 should not be relied on.");
657 #endif /* HAVE_WORKING_TZSET */
660 inittimezone(PyObject
*m
) {
661 /* This code moved from inittime wholesale to allow calling it from
662 time_tzset. In the future, some parts of it can be moved back
663 (for platforms that don't HAVE_WORKING_TZSET, when we know what they
664 are), and the extraneous calls to tzset(3) should be removed.
665 I haven't done this yet, as I don't want to change this code as
666 little as possible when introducing the time.tzset and time.tzsetwall
667 methods. This should simply be a method of doing the following once,
668 at the top of this function and removing the call to tzset() from
675 And I'm lazy and hate C so nyer.
677 #if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
680 PyModule_AddIntConstant(m
, "timezone", _timezone
);
681 #else /* !PYOS_OS2 */
682 PyModule_AddIntConstant(m
, "timezone", timezone
);
683 #endif /* PYOS_OS2 */
685 PyModule_AddIntConstant(m
, "altzone", altzone
);
688 PyModule_AddIntConstant(m
, "altzone", _timezone
-3600);
689 #else /* !PYOS_OS2 */
690 PyModule_AddIntConstant(m
, "altzone", timezone
-3600);
691 #endif /* PYOS_OS2 */
693 PyModule_AddIntConstant(m
, "daylight", daylight
);
694 PyModule_AddObject(m
, "tzname",
695 Py_BuildValue("(zz)", tzname
[0], tzname
[1]));
696 #else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
697 #ifdef HAVE_STRUCT_TM_TM_ZONE
699 #define YEAR ((time_t)((365 * 24 + 6) * 3600))
702 long janzone
, julyzone
;
703 char janname
[10], julyname
[10];
704 t
= (time((time_t *)0) / YEAR
) * YEAR
;
706 janzone
= -p
->tm_gmtoff
;
707 strncpy(janname
, p
->tm_zone
? p
->tm_zone
: " ", 9);
711 julyzone
= -p
->tm_gmtoff
;
712 strncpy(julyname
, p
->tm_zone
? p
->tm_zone
: " ", 9);
715 if( janzone
< julyzone
) {
716 /* DST is reversed in the southern hemisphere */
717 PyModule_AddIntConstant(m
, "timezone", julyzone
);
718 PyModule_AddIntConstant(m
, "altzone", janzone
);
719 PyModule_AddIntConstant(m
, "daylight",
720 janzone
!= julyzone
);
721 PyModule_AddObject(m
, "tzname",
722 Py_BuildValue("(zz)",
725 PyModule_AddIntConstant(m
, "timezone", janzone
);
726 PyModule_AddIntConstant(m
, "altzone", julyzone
);
727 PyModule_AddIntConstant(m
, "daylight",
728 janzone
!= julyzone
);
729 PyModule_AddObject(m
, "tzname",
730 Py_BuildValue("(zz)",
735 #endif /* HAVE_STRUCT_TM_TM_ZONE */
738 PyModule_AddIntConstant(m
, "timezone", _timezone
);
739 PyModule_AddIntConstant(m
, "altzone", _timezone
-3600);
740 PyModule_AddIntConstant(m
, "daylight", _daylight
);
741 PyModule_AddObject(m
, "tzname",
742 Py_BuildValue("(zz)", _tzname
[0], _tzname
[1]));
743 #endif /* __CYGWIN__ */
744 #endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
748 static PyMethodDef time_methods
[] = {
749 {"time", time_time
, METH_NOARGS
, time_doc
},
751 {"clock", time_clock
, METH_NOARGS
, clock_doc
},
753 {"sleep", time_sleep
, METH_VARARGS
, sleep_doc
},
754 {"gmtime", time_gmtime
, METH_VARARGS
, gmtime_doc
},
755 {"localtime", time_localtime
, METH_VARARGS
, localtime_doc
},
756 {"asctime", time_asctime
, METH_VARARGS
, asctime_doc
},
757 {"ctime", time_ctime
, METH_VARARGS
, ctime_doc
},
759 {"mktime", time_mktime
, METH_O
, mktime_doc
},
762 {"strftime", time_strftime
, METH_VARARGS
, strftime_doc
},
764 {"strptime", time_strptime
, METH_VARARGS
, strptime_doc
},
765 #ifdef HAVE_WORKING_TZSET
766 {"tzset", time_tzset
, METH_NOARGS
, tzset_doc
},
768 {NULL
, NULL
} /* sentinel */
772 PyDoc_STRVAR(module_doc
,
773 "This module provides various functions to manipulate time values.\n\
775 There are two standard representations of time. One is the number\n\
776 of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
777 or a floating point number (to represent fractions of seconds).\n\
778 The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
779 The actual value can be retrieved by calling gmtime(0).\n\
781 The other representation is a tuple of 9 integers giving local time.\n\
782 The tuple items are:\n\
783 year (four digits, e.g. 1998)\n\
789 weekday (0-6, Monday is 0)\n\
790 Julian day (day in the year, 1-366)\n\
791 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
792 If the DST flag is 0, the time is given in the regular time zone;\n\
793 if it is 1, the time is given in the DST time zone;\n\
794 if it is -1, mktime() should guess based on the date and time.\n\
798 timezone -- difference in seconds between UTC and local standard time\n\
799 altzone -- difference in seconds between UTC and local DST time\n\
800 daylight -- whether local time should reflect DST\n\
801 tzname -- tuple of (standard time zone name, DST time zone name)\n\
805 time() -- return current time in seconds since the Epoch as a float\n\
806 clock() -- return CPU time since process start as a float\n\
807 sleep() -- delay for a number of seconds given as a float\n\
808 gmtime() -- convert seconds since Epoch to UTC tuple\n\
809 localtime() -- convert seconds since Epoch to local time tuple\n\
810 asctime() -- convert time tuple to string\n\
811 ctime() -- convert time in seconds to string\n\
812 mktime() -- convert local time tuple to seconds since Epoch\n\
813 strftime() -- convert time tuple to string according to format specification\n\
814 strptime() -- parse string to time tuple according to format specification\n\
815 tzset() -- change the local timezone");
823 m
= Py_InitModule3("time", time_methods
, module_doc
);
827 /* Accept 2-digit dates unless PYTHONY2K is set and non-empty */
828 p
= Py_GETENV("PYTHONY2K");
829 PyModule_AddIntConstant(m
, "accept2dyear", (long) (!p
|| !*p
));
830 /* Squirrel away the module's dictionary for the y2k check */
831 moddict
= PyModule_GetDict(m
);
834 /* Set, or reset, module variables like time.timezone */
838 /* Helper to allow interrupts for Windows.
839 If Ctrl+C event delivered while not sleeping
842 main_thread
= PyThread_get_thread_ident();
843 hInterruptEvent
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
844 SetConsoleCtrlHandler( PyCtrlHandler
, TRUE
);
845 #endif /* MS_WINDOWS */
847 PyStructSequence_InitType(&StructTimeType
,
848 &struct_time_type_desc
);
850 Py_INCREF(&StructTimeType
);
851 PyModule_AddObject(m
, "struct_time", (PyObject
*) &StructTimeType
);
856 /* Implement floattime() for various platforms */
861 /* There are three ways to get the time:
862 (1) gettimeofday() -- resolution in microseconds
863 (2) ftime() -- resolution in milliseconds
864 (3) time() -- resolution in seconds
865 In all cases the return value is a float in seconds.
866 Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may
867 fail, so we fall back on ftime() or time().
868 Note: clock resolution does not imply clock accuracy! */
869 #ifdef HAVE_GETTIMEOFDAY
872 #ifdef GETTIMEOFDAY_NO_TZ
873 if (gettimeofday(&t
) == 0)
874 return (double)t
.tv_sec
+ t
.tv_usec
*0.000001;
875 #else /* !GETTIMEOFDAY_NO_TZ */
876 if (gettimeofday(&t
, (struct timezone
*)NULL
) == 0)
877 return (double)t
.tv_sec
+ t
.tv_usec
*0.000001;
878 #endif /* !GETTIMEOFDAY_NO_TZ */
881 #endif /* !HAVE_GETTIMEOFDAY */
883 #if defined(HAVE_FTIME)
886 return (double)t
.time
+ (double)t
.millitm
* (double)0.001;
887 #else /* !HAVE_FTIME */
891 #endif /* !HAVE_FTIME */
896 /* Implement floatsleep() for various platforms.
897 When interrupted (or when another error occurs), return -1 and
898 set an exception; else return 0. */
901 floatsleep(double secs
)
903 /* XXX Should test for MS_WINDOWS first! */
904 #if defined(HAVE_SELECT) && !defined(__BEOS__) && !defined(__EMX__)
907 frac
= fmod(secs
, 1.0);
909 t
.tv_sec
= (long)secs
;
910 t
.tv_usec
= (long)(frac
*1000000.0);
911 Py_BEGIN_ALLOW_THREADS
912 if (select(0, (fd_set
*)0, (fd_set
*)0, (fd_set
*)0, &t
) != 0) {
914 if (errno
!= EINTR
) {
919 PyErr_SetFromErrno(PyExc_IOError
);
924 #elif defined(__WATCOMC__) && !defined(__QNX__)
925 /* XXX Can't interrupt this sleep */
926 Py_BEGIN_ALLOW_THREADS
927 delay((int)(secs
* 1000 + 0.5)); /* delay() uses milliseconds */
929 #elif defined(MS_WINDOWS)
931 double millisecs
= secs
* 1000.0;
932 unsigned long ul_millis
;
934 if (millisecs
> (double)ULONG_MAX
) {
935 PyErr_SetString(PyExc_OverflowError
,
936 "sleep length is too large");
939 Py_BEGIN_ALLOW_THREADS
940 /* Allow sleep(0) to maintain win32 semantics, and as decreed
941 * by Guido, only the main thread can be interrupted.
943 ul_millis
= (unsigned long)millisecs
;
944 if (ul_millis
== 0 ||
945 main_thread
!= PyThread_get_thread_ident())
949 ResetEvent(hInterruptEvent
);
950 rc
= WaitForSingleObject(hInterruptEvent
, ul_millis
);
951 if (rc
== WAIT_OBJECT_0
) {
952 /* Yield to make sure real Python signal
958 PyErr_SetFromErrno(PyExc_IOError
);
964 #elif defined(PYOS_OS2)
965 /* This Sleep *IS* Interruptable by Exceptions */
966 Py_BEGIN_ALLOW_THREADS
967 if (DosSleep(secs
* 1000) != NO_ERROR
) {
969 PyErr_SetFromErrno(PyExc_IOError
);
973 #elif defined(__BEOS__)
974 /* This sleep *CAN BE* interrupted. */
980 Py_BEGIN_ALLOW_THREADS
981 /* BeOS snooze() is in microseconds... */
982 if( snooze( (bigtime_t
)( secs
* 1000.0 * 1000.0 ) ) == B_INTERRUPTED
) {
984 PyErr_SetFromErrno( PyExc_IOError
);
989 #elif defined(RISCOS)
992 Py_BEGIN_ALLOW_THREADS
993 /* This sleep *CAN BE* interrupted. */
994 if ( riscos_sleep(secs
) )
999 double millisecs
= secs
* 1000.0;
1000 if (millisecs
> (double)LONG_MAX
) {
1001 PyErr_SetString(PyExc_OverflowError
, "sleep length is too large");
1004 /* This sleep *CAN BE* interrupted. */
1005 Py_BEGIN_ALLOW_THREADS
1006 if(sleep((long)millisecs
) < 0){
1008 PyErr_SetFromErrno(PyExc_IOError
);
1011 Py_END_ALLOW_THREADS
1014 /* XXX Can't interrupt this sleep */
1015 Py_BEGIN_ALLOW_THREADS
1017 Py_END_ALLOW_THREADS