8
#define TZNAME_ENCODING "utf-8"
11
#if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_FTIME)
13
* floattime falls back to ftime when getttimeofday fails because the latter
14
* might fail on some platforms. This fallback is unwanted on MacOSX because
15
* that makes it impossible to use a binary build on OSX 10.4 on earlier
16
* releases of the OS. Therefore claim we don't support ftime.
24
#ifdef HAVE_SYS_TYPES_H
25
#include <sys/types.h>
26
#endif /* HAVE_SYS_TYPES_H */
33
#include <sys/timeb.h>
34
#if !defined(MS_WINDOWS) && !defined(PYOS_OS2)
35
extern int ftime(struct timeb *);
36
#endif /* MS_WINDOWS */
37
#endif /* HAVE_FTIME */
39
#if defined(__WATCOMC__) && !defined(__QNX__)
43
#define WIN32_LEAN_AND_MEAN
47
/* helper to allow us to interrupt sleep() on Windows*/
48
static HANDLE hInterruptEvent = NULL;
49
static BOOL WINAPI PyCtrlHandler(DWORD dwCtrlType)
51
SetEvent(hInterruptEvent);
52
/* allow other default handlers to be called.
53
Default Python handler will setup the
54
KeyboardInterrupt exception.
58
static long main_thread;
60
#if defined(__BORLANDC__)
61
/* These overrides not needed for Win32 */
62
#define timezone _timezone
63
#define tzname _tzname
64
#define daylight _daylight
65
#endif /* __BORLANDC__ */
66
#endif /* MS_WINDOWS */
67
#endif /* !__WATCOMC__ || __QNX__ */
69
#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
70
/* Win32 has better clock replacement; we have our own version below. */
72
#undef TZNAME_ENCODING
73
#define TZNAME_ENCODING "mbcs"
74
#endif /* MS_WINDOWS && !defined(__BORLANDC__) */
82
#if defined(PYCC_VACPP)
86
/* Forward declarations */
87
static int floatsleep(double);
88
static double floattime(void);
91
static PyObject *moddict;
93
/* Exposed in timefuncs.h. */
95
_PyTime_DoubleToTimet(double x)
101
/* How much info did we lose? time_t may be an integral or
102
* floating type, and we don't know which. If it's integral,
103
* we don't know whether C truncates, rounds, returns the floor,
104
* etc. If we lost a second or more, the C rounding is
105
* unreasonable, or the input just doesn't fit in a time_t;
106
* call it an error regardless. Note that the original cast to
107
* time_t can cause a C error too, but nothing we can do to
110
diff = x - (double)result;
111
if (diff <= -1.0 || diff >= 1.0) {
112
PyErr_SetString(PyExc_ValueError,
113
"timestamp out of range for platform time_t");
120
time_time(PyObject *self, PyObject *unused)
125
PyErr_SetFromErrno(PyExc_IOError);
128
return PyFloat_FromDouble(secs);
131
PyDoc_STRVAR(time_doc,
132
"time() -> floating point number\n\
134
Return the current time in seconds since the Epoch.\n\
135
Fractions of a second may be present if the system clock provides them.");
139
#ifndef CLOCKS_PER_SEC
141
#define CLOCKS_PER_SEC CLK_TCK
143
#define CLOCKS_PER_SEC 1000000
148
time_clock(PyObject *self, PyObject *unused)
150
return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC);
152
#endif /* HAVE_CLOCK */
154
#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
155
/* Due to Mark Hammond and Tim Peters */
157
time_clock(PyObject *self, PyObject *unused)
159
static LARGE_INTEGER ctrStart;
160
static double divisor = 0.0;
164
if (divisor == 0.0) {
166
QueryPerformanceCounter(&ctrStart);
167
if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
168
/* Unlikely to happen - this works on all intel
169
machines at least! Revert to clock() */
170
return PyFloat_FromDouble(((double)clock()) /
173
divisor = (double)freq.QuadPart;
175
QueryPerformanceCounter(&now);
176
diff = (double)(now.QuadPart - ctrStart.QuadPart);
177
return PyFloat_FromDouble(diff / divisor);
180
#define HAVE_CLOCK /* So it gets included in the methods */
181
#endif /* MS_WINDOWS && !defined(__BORLANDC__) */
184
PyDoc_STRVAR(clock_doc,
185
"clock() -> floating point number\n\
187
Return the CPU time or real time since the start of the process or since\n\
188
the first call to clock(). This has as much precision as the system\n\
193
time_sleep(PyObject *self, PyObject *args)
196
if (!PyArg_ParseTuple(args, "d:sleep", &secs))
198
if (floatsleep(secs) != 0)
204
PyDoc_STRVAR(sleep_doc,
207
Delay execution for a given number of seconds. The argument may be\n\
208
a floating point number for subsecond precision.");
210
static PyStructSequence_Field struct_time_type_fields[] = {
223
static PyStructSequence_Desc struct_time_type_desc = {
226
struct_time_type_fields,
230
static int initialized;
231
static PyTypeObject StructTimeType;
234
tmtotuple(struct tm *p)
236
PyObject *v = PyStructSequence_New(&StructTimeType);
240
#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val))
242
SET(0, p->tm_year + 1900);
243
SET(1, p->tm_mon + 1); /* Want January == 1 */
248
SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
249
SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
252
if (PyErr_Occurred()) {
261
structtime_totuple(PyObject *t)
265
PyObject *v = PyTuple_New(9);
269
for (i=0; i<9; i++) {
270
x = PyStructSequence_GET_ITEM(t, i);
272
PyTuple_SET_ITEM(v, i, x);
275
if (PyErr_Occurred()) {
284
time_convert(double when, struct tm * (*function)(const time_t *))
287
time_t whent = _PyTime_DoubleToTimet(when);
289
if (whent == (time_t)-1 && PyErr_Occurred())
292
p = function(&whent);
298
return PyErr_SetFromErrno(PyExc_ValueError);
303
/* Parse arg tuple that can contain an optional float-or-None value;
304
format needs to be "|O:name".
305
Returns non-zero on success (parallels PyArg_ParseTuple).
308
parse_time_double_args(PyObject *args, char *format, double *pwhen)
312
if (!PyArg_ParseTuple(args, format, &ot))
314
if (ot == NULL || ot == Py_None)
315
*pwhen = floattime();
317
double when = PyFloat_AsDouble(ot);
318
if (PyErr_Occurred())
326
time_gmtime(PyObject *self, PyObject *args)
329
if (!parse_time_double_args(args, "|O:gmtime", &when))
331
return time_convert(when, gmtime);
334
PyDoc_STRVAR(gmtime_doc,
335
"gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,\n\
336
tm_sec, tm_wday, tm_yday, tm_isdst)\n\
338
Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
339
GMT). When 'seconds' is not passed in, convert the current time instead.");
342
time_localtime(PyObject *self, PyObject *args)
345
if (!parse_time_double_args(args, "|O:localtime", &when))
347
return time_convert(when, localtime);
350
PyDoc_STRVAR(localtime_doc,
351
"localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\
352
tm_sec,tm_wday,tm_yday,tm_isdst)\n\
354
Convert seconds since the Epoch to a time tuple expressing local time.\n\
355
When 'seconds' is not passed in, convert the current time instead.");
358
gettmarg(PyObject *args, struct tm *p)
363
memset((void *) p, '\0', sizeof(struct tm));
365
if (PyTuple_Check(args)) {
369
else if (Py_TYPE(args) == &StructTimeType) {
370
t = structtime_totuple(args);
373
PyErr_SetString(PyExc_TypeError,
374
"Tuple or struct_time argument required");
378
if (t == NULL || !PyArg_ParseTuple(t, "iiiiiiiii",
394
PyObject *accept = PyDict_GetItemString(moddict,
396
if (accept == NULL || !PyLong_CheckExact(accept) ||
397
!PyObject_IsTrue(accept)) {
398
PyErr_SetString(PyExc_ValueError,
399
"year >= 1900 required");
402
if (69 <= y && y <= 99)
404
else if (0 <= y && y <= 68)
407
PyErr_SetString(PyExc_ValueError,
408
"year out of range");
412
p->tm_year = y - 1900;
414
p->tm_wday = (p->tm_wday + 1) % 7;
421
time_strftime(PyObject *self, PyObject *args)
423
PyObject *tup = NULL;
427
size_t fmtlen, buflen;
431
memset((void *) &buf, '\0', sizeof(buf));
433
/* Will always expect a unicode string to be passed as format.
434
Given that there's no str type anymore in py3k this seems safe.
436
if (!PyArg_ParseTuple(args, "U|O:strftime", &format, &tup))
440
time_t tt = time(NULL);
441
buf = *localtime(&tt);
442
} else if (!gettmarg(tup, &buf))
445
/* Checks added to make sure strftime() does not crash Python by
446
indexing blindly into some array for a textual representation
447
by some bad index (fixes bug #897625).
449
Also support values of zero from Python code for arguments in which
450
that is out of range by forcing that value to the lowest value that
451
is valid (fixed bug #1520914).
453
Valid ranges based on what is allowed in struct tm:
455
- tm_year: [0, max(int)] (1)
456
- tm_mon: [0, 11] (2)
461
- tm_wday: [0, 6] (1)
462
- tm_yday: [0, 365] (2)
463
- tm_isdst: [-max(int), max(int)]
465
(1) gettmarg() handles bounds-checking.
466
(2) Python's acceptable range is one greater than the range in C,
467
thus need to check against automatic decrement by gettmarg().
469
if (buf.tm_mon == -1)
471
else if (buf.tm_mon < 0 || buf.tm_mon > 11) {
472
PyErr_SetString(PyExc_ValueError, "month out of range");
475
if (buf.tm_mday == 0)
477
else if (buf.tm_mday < 0 || buf.tm_mday > 31) {
478
PyErr_SetString(PyExc_ValueError, "day of month out of range");
481
if (buf.tm_hour < 0 || buf.tm_hour > 23) {
482
PyErr_SetString(PyExc_ValueError, "hour out of range");
485
if (buf.tm_min < 0 || buf.tm_min > 59) {
486
PyErr_SetString(PyExc_ValueError, "minute out of range");
489
if (buf.tm_sec < 0 || buf.tm_sec > 61) {
490
PyErr_SetString(PyExc_ValueError, "seconds out of range");
493
/* tm_wday does not need checking of its upper-bound since taking
494
``% 7`` in gettmarg() automatically restricts the range. */
495
if (buf.tm_wday < 0) {
496
PyErr_SetString(PyExc_ValueError, "day of week out of range");
499
if (buf.tm_yday == -1)
501
else if (buf.tm_yday < 0 || buf.tm_yday > 365) {
502
PyErr_SetString(PyExc_ValueError, "day of year out of range");
505
if (buf.tm_isdst < -1 || buf.tm_isdst > 1) {
506
PyErr_SetString(PyExc_ValueError,
507
"daylight savings flag out of range");
511
/* Convert the unicode string to an ascii one */
512
format = PyUnicode_AsEncodedString(format, TZNAME_ENCODING, NULL);
515
fmt = PyBytes_AS_STRING(format);
518
/* check that the format string contains only valid directives */
519
for(outbuf = strchr(fmt, '%');
521
outbuf = strchr(outbuf+2, '%'))
524
++outbuf; /* not documented by python, */
525
if (outbuf[1]=='\0' ||
526
!strchr("aAbBcdfHIjmMpSUwWxXyYzZ%", outbuf[1]))
528
PyErr_SetString(PyExc_ValueError, "Invalid format string");
534
fmtlen = strlen(fmt);
536
/* I hate these functions that presume you know how big the output
537
* will be ahead of time...
539
for (i = 1024; ; i += i) {
540
outbuf = (char *)PyMem_Malloc(i);
541
if (outbuf == NULL) {
543
return PyErr_NoMemory();
545
buflen = strftime(outbuf, i, fmt, &buf);
546
if (buflen > 0 || i >= 256 * fmtlen) {
547
/* If the buffer is 256 times as long as the format,
548
it's probably not failing for lack of room!
549
More likely, the format yields an empty result,
550
e.g. an empty format, or %Z when the timezone
553
ret = PyUnicode_Decode(outbuf, buflen,
554
TZNAME_ENCODING, NULL);
560
#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
561
/* VisualStudio .NET 2005 does this properly */
562
if (buflen == 0 && errno == EINVAL) {
563
PyErr_SetString(PyExc_ValueError, "Invalid format string");
571
PyDoc_STRVAR(strftime_doc,
572
"strftime(format[, tuple]) -> string\n\
574
Convert a time tuple to a string according to a format specification.\n\
575
See the library reference manual for formatting codes. When the time tuple\n\
576
is not present, current time as returned by localtime() is used.");
577
#endif /* HAVE_STRFTIME */
580
time_strptime(PyObject *self, PyObject *args)
582
PyObject *strptime_module = PyImport_ImportModuleNoBlock("_strptime");
583
PyObject *strptime_result;
585
if (!strptime_module)
587
strptime_result = PyObject_CallMethod(strptime_module, "_strptime_time", "O", args);
588
Py_DECREF(strptime_module);
589
return strptime_result;
592
PyDoc_STRVAR(strptime_doc,
593
"strptime(string, format) -> struct_time\n\
595
Parse a string to a time tuple according to a format specification.\n\
596
See the library reference manual for formatting codes (same as strftime()).");
600
time_asctime(PyObject *self, PyObject *args)
602
PyObject *tup = NULL;
605
if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
608
time_t tt = time(NULL);
609
buf = *localtime(&tt);
610
} else if (!gettmarg(tup, &buf))
615
return PyUnicode_FromString(p);
618
PyDoc_STRVAR(asctime_doc,
619
"asctime([tuple]) -> string\n\
621
Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
622
When the time tuple is not present, current time as returned by localtime()\n\
626
time_ctime(PyObject *self, PyObject *args)
632
if (!PyArg_UnpackTuple(args, "ctime", 0, 1, &ot))
634
if (ot == NULL || ot == Py_None)
637
double dt = PyFloat_AsDouble(ot);
638
if (PyErr_Occurred())
640
tt = _PyTime_DoubleToTimet(dt);
641
if (tt == (time_t)-1 && PyErr_Occurred())
646
PyErr_SetString(PyExc_ValueError, "unconvertible time");
651
return PyUnicode_FromString(p);
654
PyDoc_STRVAR(ctime_doc,
655
"ctime(seconds) -> string\n\
657
Convert a time in seconds since the Epoch to a string in local time.\n\
658
This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
659
not present, current time as returned by localtime() is used.");
663
time_mktime(PyObject *self, PyObject *tup)
667
if (!gettmarg(tup, &buf))
670
if (tt == (time_t)(-1)) {
671
PyErr_SetString(PyExc_OverflowError,
672
"mktime argument out of range");
675
return PyFloat_FromDouble((double)tt);
678
PyDoc_STRVAR(mktime_doc,
679
"mktime(tuple) -> floating point number\n\
681
Convert a time tuple in local time to seconds since the Epoch.");
682
#endif /* HAVE_MKTIME */
684
#ifdef HAVE_WORKING_TZSET
685
static void PyInit_timezone(PyObject *module);
688
time_tzset(PyObject *self, PyObject *unused)
692
m = PyImport_ImportModuleNoBlock("time");
699
/* Reset timezone, altzone, daylight and tzname */
707
PyDoc_STRVAR(tzset_doc,
710
Initialize, or reinitialize, the local timezone to the value stored in\n\
711
os.environ['TZ']. The TZ environment variable should be specified in\n\
712
standard Unix timezone format as documented in the tzset man page\n\
713
(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
714
fall back to UTC. If the TZ environment variable is not set, the local\n\
715
timezone is set to the systems best guess of wallclock time.\n\
716
Changing the TZ environment variable without calling tzset *may* change\n\
717
the local timezone used by methods such as localtime, but this behaviour\n\
718
should not be relied on.");
719
#endif /* HAVE_WORKING_TZSET */
722
PyInit_timezone(PyObject *m) {
723
/* This code moved from PyInit_time wholesale to allow calling it from
724
time_tzset. In the future, some parts of it can be moved back
725
(for platforms that don't HAVE_WORKING_TZSET, when we know what they
726
are), and the extraneous calls to tzset(3) should be removed.
727
I haven't done this yet, as I don't want to change this code as
728
little as possible when introducing the time.tzset and time.tzsetwall
729
methods. This should simply be a method of doing the following once,
730
at the top of this function and removing the call to tzset() from
737
And I'm lazy and hate C so nyer.
739
#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
740
PyObject *otz0, *otz1;
743
PyModule_AddIntConstant(m, "timezone", _timezone);
744
#else /* !PYOS_OS2 */
745
PyModule_AddIntConstant(m, "timezone", timezone);
746
#endif /* PYOS_OS2 */
748
PyModule_AddIntConstant(m, "altzone", altzone);
751
PyModule_AddIntConstant(m, "altzone", _timezone-3600);
752
#else /* !PYOS_OS2 */
753
PyModule_AddIntConstant(m, "altzone", timezone-3600);
754
#endif /* PYOS_OS2 */
756
PyModule_AddIntConstant(m, "daylight", daylight);
757
otz0 = PyUnicode_Decode(tzname[0], strlen(tzname[0]), TZNAME_ENCODING, NULL);
758
otz1 = PyUnicode_Decode(tzname[1], strlen(tzname[1]), TZNAME_ENCODING, NULL);
759
PyModule_AddObject(m, "tzname", Py_BuildValue("(NN)", otz0, otz1));
760
#else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
761
#ifdef HAVE_STRUCT_TM_TM_ZONE
763
#define YEAR ((time_t)((365 * 24 + 6) * 3600))
766
long janzone, julyzone;
767
char janname[10], julyname[10];
768
t = (time((time_t *)0) / YEAR) * YEAR;
770
janzone = -p->tm_gmtoff;
771
strncpy(janname, p->tm_zone ? p->tm_zone : " ", 9);
775
julyzone = -p->tm_gmtoff;
776
strncpy(julyname, p->tm_zone ? p->tm_zone : " ", 9);
779
if( janzone < julyzone ) {
780
/* DST is reversed in the southern hemisphere */
781
PyModule_AddIntConstant(m, "timezone", julyzone);
782
PyModule_AddIntConstant(m, "altzone", janzone);
783
PyModule_AddIntConstant(m, "daylight",
784
janzone != julyzone);
785
PyModule_AddObject(m, "tzname",
786
Py_BuildValue("(zz)",
789
PyModule_AddIntConstant(m, "timezone", janzone);
790
PyModule_AddIntConstant(m, "altzone", julyzone);
791
PyModule_AddIntConstant(m, "daylight",
792
janzone != julyzone);
793
PyModule_AddObject(m, "tzname",
794
Py_BuildValue("(zz)",
799
#endif /* HAVE_STRUCT_TM_TM_ZONE */
802
PyModule_AddIntConstant(m, "timezone", _timezone);
803
PyModule_AddIntConstant(m, "altzone", _timezone-3600);
804
PyModule_AddIntConstant(m, "daylight", _daylight);
805
PyModule_AddObject(m, "tzname",
806
Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
807
#endif /* __CYGWIN__ */
808
#endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
812
static PyMethodDef time_methods[] = {
813
{"time", time_time, METH_NOARGS, time_doc},
815
{"clock", time_clock, METH_NOARGS, clock_doc},
817
{"sleep", time_sleep, METH_VARARGS, sleep_doc},
818
{"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
819
{"localtime", time_localtime, METH_VARARGS, localtime_doc},
820
{"asctime", time_asctime, METH_VARARGS, asctime_doc},
821
{"ctime", time_ctime, METH_VARARGS, ctime_doc},
823
{"mktime", time_mktime, METH_O, mktime_doc},
826
{"strftime", time_strftime, METH_VARARGS, strftime_doc},
828
{"strptime", time_strptime, METH_VARARGS, strptime_doc},
829
#ifdef HAVE_WORKING_TZSET
830
{"tzset", time_tzset, METH_NOARGS, tzset_doc},
832
{NULL, NULL} /* sentinel */
836
PyDoc_STRVAR(module_doc,
837
"This module provides various functions to manipulate time values.\n\
839
There are two standard representations of time. One is the number\n\
840
of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
841
or a floating point number (to represent fractions of seconds).\n\
842
The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
843
The actual value can be retrieved by calling gmtime(0).\n\
845
The other representation is a tuple of 9 integers giving local time.\n\
846
The tuple items are:\n\
847
year (four digits, e.g. 1998)\n\
853
weekday (0-6, Monday is 0)\n\
854
Julian day (day in the year, 1-366)\n\
855
DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
856
If the DST flag is 0, the time is given in the regular time zone;\n\
857
if it is 1, the time is given in the DST time zone;\n\
858
if it is -1, mktime() should guess based on the date and time.\n\
862
timezone -- difference in seconds between UTC and local standard time\n\
863
altzone -- difference in seconds between UTC and local DST time\n\
864
daylight -- whether local time should reflect DST\n\
865
tzname -- tuple of (standard time zone name, DST time zone name)\n\
869
time() -- return current time in seconds since the Epoch as a float\n\
870
clock() -- return CPU time since process start as a float\n\
871
sleep() -- delay for a number of seconds given as a float\n\
872
gmtime() -- convert seconds since Epoch to UTC tuple\n\
873
localtime() -- convert seconds since Epoch to local time tuple\n\
874
asctime() -- convert time tuple to string\n\
875
ctime() -- convert time in seconds to string\n\
876
mktime() -- convert local time tuple to seconds since Epoch\n\
877
strftime() -- convert time tuple to string according to format specification\n\
878
strptime() -- parse string to time tuple according to format specification\n\
879
tzset() -- change the local timezone");
883
static struct PyModuleDef timemodule = {
884
PyModuleDef_HEAD_INIT,
900
m = PyModule_Create(&timemodule);
904
/* Accept 2-digit dates unless PYTHONY2K is set and non-empty */
905
p = Py_GETENV("PYTHONY2K");
906
PyModule_AddIntConstant(m, "accept2dyear", (long) (!p || !*p));
907
/* Squirrel away the module's dictionary for the y2k check */
908
moddict = PyModule_GetDict(m);
911
/* Set, or reset, module variables like time.timezone */
915
/* Helper to allow interrupts for Windows.
916
If Ctrl+C event delivered while not sleeping
919
main_thread = PyThread_get_thread_ident();
920
hInterruptEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
921
SetConsoleCtrlHandler( PyCtrlHandler, TRUE);
922
#endif /* MS_WINDOWS */
924
PyStructSequence_InitType(&StructTimeType,
925
&struct_time_type_desc);
927
Py_INCREF(&StructTimeType);
928
PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
934
/* Implement floattime() for various platforms */
939
/* There are three ways to get the time:
940
(1) gettimeofday() -- resolution in microseconds
941
(2) ftime() -- resolution in milliseconds
942
(3) time() -- resolution in seconds
943
In all cases the return value is a float in seconds.
944
Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may
945
fail, so we fall back on ftime() or time().
946
Note: clock resolution does not imply clock accuracy! */
947
#ifdef HAVE_GETTIMEOFDAY
950
#ifdef GETTIMEOFDAY_NO_TZ
951
if (gettimeofday(&t) == 0)
952
return (double)t.tv_sec + t.tv_usec*0.000001;
953
#else /* !GETTIMEOFDAY_NO_TZ */
954
if (gettimeofday(&t, (struct timezone *)NULL) == 0)
955
return (double)t.tv_sec + t.tv_usec*0.000001;
956
#endif /* !GETTIMEOFDAY_NO_TZ */
959
#endif /* !HAVE_GETTIMEOFDAY */
961
#if defined(HAVE_FTIME)
964
return (double)t.time + (double)t.millitm * (double)0.001;
965
#else /* !HAVE_FTIME */
969
#endif /* !HAVE_FTIME */
974
/* Implement floatsleep() for various platforms.
975
When interrupted (or when another error occurs), return -1 and
976
set an exception; else return 0. */
979
floatsleep(double secs)
981
/* XXX Should test for MS_WINDOWS first! */
982
#if defined(HAVE_SELECT) && !defined(__EMX__)
985
frac = fmod(secs, 1.0);
987
t.tv_sec = (long)secs;
988
t.tv_usec = (long)(frac*1000000.0);
989
Py_BEGIN_ALLOW_THREADS
990
if (select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t) != 0) {
992
if (errno != EINTR) {
997
PyErr_SetFromErrno(PyExc_IOError);
1001
Py_END_ALLOW_THREADS
1002
#elif defined(__WATCOMC__) && !defined(__QNX__)
1003
/* XXX Can't interrupt this sleep */
1004
Py_BEGIN_ALLOW_THREADS
1005
delay((int)(secs * 1000 + 0.5)); /* delay() uses milliseconds */
1006
Py_END_ALLOW_THREADS
1007
#elif defined(MS_WINDOWS)
1009
double millisecs = secs * 1000.0;
1010
unsigned long ul_millis;
1012
if (millisecs > (double)ULONG_MAX) {
1013
PyErr_SetString(PyExc_OverflowError,
1014
"sleep length is too large");
1017
Py_BEGIN_ALLOW_THREADS
1018
/* Allow sleep(0) to maintain win32 semantics, and as decreed
1019
* by Guido, only the main thread can be interrupted.
1021
ul_millis = (unsigned long)millisecs;
1022
if (ul_millis == 0 ||
1023
main_thread != PyThread_get_thread_ident())
1027
ResetEvent(hInterruptEvent);
1028
rc = WaitForSingleObject(hInterruptEvent, ul_millis);
1029
if (rc == WAIT_OBJECT_0) {
1030
/* Yield to make sure real Python signal
1036
PyErr_SetFromErrno(PyExc_IOError);
1040
Py_END_ALLOW_THREADS
1042
#elif defined(PYOS_OS2)
1043
/* This Sleep *IS* Interruptable by Exceptions */
1044
Py_BEGIN_ALLOW_THREADS
1045
if (DosSleep(secs * 1000) != NO_ERROR) {
1047
PyErr_SetFromErrno(PyExc_IOError);
1050
Py_END_ALLOW_THREADS
1051
#elif defined(PLAN9)
1053
double millisecs = secs * 1000.0;
1054
if (millisecs > (double)LONG_MAX) {
1055
PyErr_SetString(PyExc_OverflowError, "sleep length is too large");
1058
/* This sleep *CAN BE* interrupted. */
1059
Py_BEGIN_ALLOW_THREADS
1060
if(sleep((long)millisecs) < 0){
1062
PyErr_SetFromErrno(PyExc_IOError);
1065
Py_END_ALLOW_THREADS
1068
/* XXX Can't interrupt this sleep */
1069
Py_BEGIN_ALLOW_THREADS
1071
Py_END_ALLOW_THREADS