blob: 161407de45946974ee477747d4a4b260cd90f190 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Time module */
2
Barry Warsaw9a2a8a81996-12-06 23:32:14 +00003#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00004
Guido van Rossum87ce7bb1998-06-09 16:30:31 +00005#include <ctype.h>
6
Victor Stinnerec895392012-04-29 02:41:27 +02007#ifdef HAVE_SYS_TIMES_H
8#include <sys/times.h>
9#endif
10
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011#ifdef HAVE_SYS_TYPES_H
Guido van Rossumb6775db1994-08-01 11:34:53 +000012#include <sys/types.h>
Victor Stinnerec895392012-04-29 02:41:27 +020013#endif
14
15#if defined(HAVE_SYS_RESOURCE_H)
16#include <sys/resource.h>
17#endif
Guido van Rossum6d946f91992-08-14 13:49:30 +000018
Guido van Rossumb6775db1994-08-01 11:34:53 +000019#ifdef QUICKWIN
20#include <io.h>
21#endif
22
Guido van Rossum7bf22de1997-12-02 20:34:19 +000023#if defined(__WATCOMC__) && !defined(__QNX__)
Guido van Rossumbceeac81996-05-23 22:53:47 +000024#include <i86.h>
25#else
Guido van Rossumcac6c721996-09-06 13:34:02 +000026#ifdef MS_WINDOWS
Mark Hammond975e3922002-07-16 01:29:19 +000027#define WIN32_LEAN_AND_MEAN
Guido van Rossum258ccd42001-03-02 06:53:29 +000028#include <windows.h>
Mark Hammond975e3922002-07-16 01:29:19 +000029#include "pythread.h"
30
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000031#if defined(__BORLANDC__)
Guido van Rossumb2fb3641996-09-07 00:47:35 +000032/* These overrides not needed for Win32 */
Guido van Rossumb6775db1994-08-01 11:34:53 +000033#define timezone _timezone
Guido van Rossumcc081121995-03-14 15:05:41 +000034#define tzname _tzname
35#define daylight _daylight
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000036#endif /* __BORLANDC__ */
Guido van Rossumcac6c721996-09-06 13:34:02 +000037#endif /* MS_WINDOWS */
Guido van Rossum7bf22de1997-12-02 20:34:19 +000038#endif /* !__WATCOMC__ || __QNX__ */
Guido van Rossum234f9421993-06-17 12:35:49 +000039
Andrew MacIntyre7bf68332002-03-03 02:59:16 +000040#if defined(PYOS_OS2)
41#define INCL_DOS
42#define INCL_ERRORS
43#include <os2.h>
44#endif
45
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000046#if defined(PYCC_VACPP)
Guido van Rossum26452411998-09-28 22:07:11 +000047#include <sys/time.h>
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000048#endif
49
Victor Stinnera8ec5ea2012-03-13 00:25:42 +010050#if defined(__APPLE__)
51#include <mach/mach_time.h>
52#endif
53
Guido van Rossum234f9421993-06-17 12:35:49 +000054/* Forward declarations */
Tim Petersdbd9ba62000-07-09 03:09:57 +000055static int floatsleep(double);
Victor Stinnerec895392012-04-29 02:41:27 +020056static PyObject* floattime(_Py_clock_info_t *info);
57
58#ifdef MS_WINDOWS
59static OSVERSIONINFOEX winver;
60#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000061
Barry Warsaw9a2a8a81996-12-06 23:32:14 +000062static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +010063time_time(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000064{
Victor Stinnerec895392012-04-29 02:41:27 +020065 return floattime(NULL);
Guido van Rossumb6775db1994-08-01 11:34:53 +000066}
67
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000068PyDoc_STRVAR(time_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +010069"time() -> floating point number\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +000070\n\
71Return the current time in seconds since the Epoch.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000072Fractions of a second may be present if the system clock provides them.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +000073
Victor Stinner85fdfa82012-01-27 00:38:48 +010074#if defined(HAVE_CLOCK)
75
76#ifndef CLOCKS_PER_SEC
77#ifdef CLK_TCK
78#define CLOCKS_PER_SEC CLK_TCK
79#else
80#define CLOCKS_PER_SEC 1000000
81#endif
82#endif
83
Victor Stinner4195b5c2012-02-08 23:03:19 +010084static PyObject *
Victor Stinnerec895392012-04-29 02:41:27 +020085floatclock(_Py_clock_info_t *info)
Victor Stinner85fdfa82012-01-27 00:38:48 +010086{
Victor Stinner4195b5c2012-02-08 23:03:19 +010087 clock_t value;
88 value = clock();
89 if (value == (clock_t)-1) {
Victor Stinner85fdfa82012-01-27 00:38:48 +010090 PyErr_SetString(PyExc_RuntimeError,
91 "the processor time used is not available "
92 "or its value cannot be represented");
Victor Stinner4195b5c2012-02-08 23:03:19 +010093 return NULL;
Victor Stinner85fdfa82012-01-27 00:38:48 +010094 }
Victor Stinnerec895392012-04-29 02:41:27 +020095 if (info) {
96 info->implementation = "clock()";
97 info->resolution = 1.0 / (double)CLOCKS_PER_SEC;
Benjamin Peterson49a69e42012-05-01 09:38:34 -040098 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +020099 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +0200100 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100101 return PyFloat_FromDouble((double)value / CLOCKS_PER_SEC);
Victor Stinner85fdfa82012-01-27 00:38:48 +0100102}
103#endif /* HAVE_CLOCK */
104
Thomas Wouters477c8d52006-05-27 19:21:47 +0000105#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
Victor Stinnerec895392012-04-29 02:41:27 +0200106#define WIN32_PERF_COUNTER
Victor Stinner9122fdd2011-07-04 13:55:40 +0200107/* Win32 has better clock replacement; we have our own version, due to Mark
108 Hammond and Tim Peters */
Victor Stinnerec895392012-04-29 02:41:27 +0200109static int
110win_perf_counter(_Py_clock_info_t *info, PyObject **result)
Guido van Rossum3917c221997-04-02 05:35:28 +0000111{
Victor Stinner8b302012012-02-07 23:29:46 +0100112 static LONGLONG cpu_frequency = 0;
Victor Stinner4195b5c2012-02-08 23:03:19 +0100113 static LONGLONG ctrStart;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 LARGE_INTEGER now;
Victor Stinner4195b5c2012-02-08 23:03:19 +0100115 double diff;
Guido van Rossum3917c221997-04-02 05:35:28 +0000116
Victor Stinner8b302012012-02-07 23:29:46 +0100117 if (cpu_frequency == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000118 LARGE_INTEGER freq;
Victor Stinner8b302012012-02-07 23:29:46 +0100119 QueryPerformanceCounter(&now);
Victor Stinner4195b5c2012-02-08 23:03:19 +0100120 ctrStart = now.QuadPart;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000121 if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
122 /* Unlikely to happen - this works on all intel
123 machines at least! Revert to clock() */
Victor Stinnerec895392012-04-29 02:41:27 +0200124 *result = NULL;
125 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 }
Victor Stinner8b302012012-02-07 23:29:46 +0100127 cpu_frequency = freq.QuadPart;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 }
129 QueryPerformanceCounter(&now);
Victor Stinner4195b5c2012-02-08 23:03:19 +0100130 diff = (double)(now.QuadPart - ctrStart);
Victor Stinnerec895392012-04-29 02:41:27 +0200131 if (info) {
132 info->implementation = "QueryPerformanceCounter()";
133 info->resolution = 1.0 / (double)cpu_frequency;
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400134 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200135 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +0200136 }
137 *result = PyFloat_FromDouble(diff / (double)cpu_frequency);
138 return 0;
Guido van Rossum3917c221997-04-02 05:35:28 +0000139}
Victor Stinner8b302012012-02-07 23:29:46 +0100140#endif
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000141
Victor Stinnerec895392012-04-29 02:41:27 +0200142#if defined(WIN32_PERF_COUNTER) || defined(HAVE_CLOCK)
143#define PYCLOCK
144static PyObject*
145pyclock(_Py_clock_info_t *info)
146{
147#ifdef WIN32_PERF_COUNTER
148 PyObject *res;
149 if (win_perf_counter(info, &res) == 0)
150 return res;
151#endif
152 return floatclock(info);
153}
154
Victor Stinner9122fdd2011-07-04 13:55:40 +0200155static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100156time_clock(PyObject *self, PyObject *unused)
Victor Stinner9122fdd2011-07-04 13:55:40 +0200157{
Victor Stinnerec895392012-04-29 02:41:27 +0200158 return pyclock(NULL);
Victor Stinner9122fdd2011-07-04 13:55:40 +0200159}
Victor Stinner9122fdd2011-07-04 13:55:40 +0200160
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000161PyDoc_STRVAR(clock_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +0100162"clock() -> floating point number\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000163\n\
164Return the CPU time or real time since the start of the process or since\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000165the first call to clock(). This has as much precision as the system\n\
166records.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000167#endif
168
Victor Stinnere0be4232011-10-25 13:06:09 +0200169#ifdef HAVE_CLOCK_GETTIME
170static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100171time_clock_gettime(PyObject *self, PyObject *args)
Victor Stinnere0be4232011-10-25 13:06:09 +0200172{
173 int ret;
Victor Stinnerb8d01692012-04-13 23:44:05 +0200174 int clk_id;
Victor Stinnere0be4232011-10-25 13:06:09 +0200175 struct timespec tp;
176
Victor Stinner4195b5c2012-02-08 23:03:19 +0100177 if (!PyArg_ParseTuple(args, "i:clock_gettime", &clk_id))
Victor Stinnere0be4232011-10-25 13:06:09 +0200178 return NULL;
179
180 ret = clock_gettime((clockid_t)clk_id, &tp);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100181 if (ret != 0) {
Victor Stinnere0be4232011-10-25 13:06:09 +0200182 PyErr_SetFromErrno(PyExc_IOError);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100183 return NULL;
184 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100185 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinnere0be4232011-10-25 13:06:09 +0200186}
187
188PyDoc_STRVAR(clock_gettime_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +0100189"clock_gettime(clk_id) -> floating point number\n\
Victor Stinnere0be4232011-10-25 13:06:09 +0200190\n\
191Return the time of the specified clock clk_id.");
Victor Stinner30d79472012-04-03 00:45:07 +0200192
193static PyObject *
194time_clock_settime(PyObject *self, PyObject *args)
195{
Victor Stinnerb8d01692012-04-13 23:44:05 +0200196 int clk_id;
Victor Stinner30d79472012-04-03 00:45:07 +0200197 PyObject *obj;
198 struct timespec tp;
199 int ret;
200
201 if (!PyArg_ParseTuple(args, "iO:clock_settime", &clk_id, &obj))
202 return NULL;
203
204 if (_PyTime_ObjectToTimespec(obj, &tp.tv_sec, &tp.tv_nsec) == -1)
205 return NULL;
206
207 ret = clock_settime((clockid_t)clk_id, &tp);
208 if (ret != 0) {
209 PyErr_SetFromErrno(PyExc_IOError);
210 return NULL;
211 }
212 Py_RETURN_NONE;
213}
214
215PyDoc_STRVAR(clock_settime_doc,
216"clock_settime(clk_id, time)\n\
217\n\
218Set the time of the specified clock clk_id.");
Victor Stinnere0be4232011-10-25 13:06:09 +0200219
Victor Stinnere0be4232011-10-25 13:06:09 +0200220static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100221time_clock_getres(PyObject *self, PyObject *args)
Victor Stinnere0be4232011-10-25 13:06:09 +0200222{
223 int ret;
Victor Stinnerb8d01692012-04-13 23:44:05 +0200224 int clk_id;
Victor Stinnere0be4232011-10-25 13:06:09 +0200225 struct timespec tp;
226
Victor Stinner4195b5c2012-02-08 23:03:19 +0100227 if (!PyArg_ParseTuple(args, "i:clock_getres", &clk_id))
Victor Stinnere0be4232011-10-25 13:06:09 +0200228 return NULL;
229
230 ret = clock_getres((clockid_t)clk_id, &tp);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100231 if (ret != 0) {
Victor Stinnere0be4232011-10-25 13:06:09 +0200232 PyErr_SetFromErrno(PyExc_IOError);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100233 return NULL;
234 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100235
236 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinnere0be4232011-10-25 13:06:09 +0200237}
238
239PyDoc_STRVAR(clock_getres_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +0100240"clock_getres(clk_id) -> floating point number\n\
Victor Stinnere0be4232011-10-25 13:06:09 +0200241\n\
242Return the resolution (precision) of the specified clock clk_id.");
Victor Stinnerb8d01692012-04-13 23:44:05 +0200243#endif /* HAVE_CLOCK_GETTIME */
Victor Stinnere0be4232011-10-25 13:06:09 +0200244
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000245static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000246time_sleep(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 double secs;
249 if (!PyArg_ParseTuple(args, "d:sleep", &secs))
250 return NULL;
Victor Stinner7f53a502011-07-05 22:00:25 +0200251 if (secs < 0) {
252 PyErr_SetString(PyExc_ValueError,
253 "sleep length must be non-negative");
254 return NULL;
255 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 if (floatsleep(secs) != 0)
257 return NULL;
258 Py_INCREF(Py_None);
259 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000260}
261
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000262PyDoc_STRVAR(sleep_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000263"sleep(seconds)\n\
264\n\
265Delay execution for a given number of seconds. The argument may be\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000266a floating point number for subsecond precision.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000267
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000268static PyStructSequence_Field struct_time_type_fields[] = {
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000269 {"tm_year", "year, for example, 1993"},
270 {"tm_mon", "month of year, range [1, 12]"},
271 {"tm_mday", "day of month, range [1, 31]"},
272 {"tm_hour", "hours, range [0, 23]"},
273 {"tm_min", "minutes, range [0, 59]"},
274 {"tm_sec", "seconds, range [0, 61])"},
275 {"tm_wday", "day of week, range [0, 6], Monday is 0"},
276 {"tm_yday", "day of year, range [1, 366]"},
277 {"tm_isdst", "1 if summer time is in effect, 0 if not, and -1 if unknown"},
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400278#ifdef HAVE_STRUCT_TM_TM_ZONE
279 {"tm_zone", "abbreviation of timezone name"},
280 {"tm_gmtoff", "offset from UTC in seconds"},
281#endif /* HAVE_STRUCT_TM_TM_ZONE */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000283};
284
285static PyStructSequence_Desc struct_time_type_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 "time.struct_time",
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000287 "The time value as returned by gmtime(), localtime(), and strptime(), and\n"
288 " accepted by asctime(), mktime() and strftime(). May be considered as a\n"
289 " sequence of 9 integers.\n\n"
290 " Note that several fields' values are not the same as those defined by\n"
291 " the C language standard for struct tm. For example, the value of the\n"
292 " field tm_year is the actual year, not year - 1900. See individual\n"
293 " fields' descriptions for details.",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000294 struct_time_type_fields,
295 9,
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000296};
Tim Peters9ad4b682002-02-13 05:14:18 +0000297
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000298static int initialized;
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000299static PyTypeObject StructTimeType;
300
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400301
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000302static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000303tmtotuple(struct tm *p)
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000304{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 PyObject *v = PyStructSequence_New(&StructTimeType);
306 if (v == NULL)
307 return NULL;
Tim Peters9ad4b682002-02-13 05:14:18 +0000308
Christian Heimes217cfd12007-12-02 14:31:20 +0000309#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val))
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000311 SET(0, p->tm_year + 1900);
312 SET(1, p->tm_mon + 1); /* Want January == 1 */
313 SET(2, p->tm_mday);
314 SET(3, p->tm_hour);
315 SET(4, p->tm_min);
316 SET(5, p->tm_sec);
317 SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
318 SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
319 SET(8, p->tm_isdst);
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400320#ifdef HAVE_STRUCT_TM_TM_ZONE
321 PyStructSequence_SET_ITEM(v, 9,
322 PyUnicode_DecodeLocale(p->tm_zone, "surrogateescape"));
323 SET(10, p->tm_gmtoff);
324#endif /* HAVE_STRUCT_TM_TM_ZONE */
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000325#undef SET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 if (PyErr_Occurred()) {
327 Py_XDECREF(v);
328 return NULL;
329 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 return v;
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000332}
333
Fred Drakef901abd2004-08-03 17:58:55 +0000334/* Parse arg tuple that can contain an optional float-or-None value;
335 format needs to be "|O:name".
336 Returns non-zero on success (parallels PyArg_ParseTuple).
337*/
338static int
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100339parse_time_t_args(PyObject *args, char *format, time_t *pwhen)
Fred Drakef901abd2004-08-03 17:58:55 +0000340{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 PyObject *ot = NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100342 time_t whent;
Fred Drakef901abd2004-08-03 17:58:55 +0000343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 if (!PyArg_ParseTuple(args, format, &ot))
345 return 0;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100346 if (ot == NULL || ot == Py_None) {
347 whent = time(NULL);
348 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 else {
Victor Stinner5d272cc2012-03-13 13:35:55 +0100350 if (_PyTime_ObjectToTime_t(ot, &whent) == -1)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100351 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 }
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100353 *pwhen = whent;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 return 1;
Fred Drakef901abd2004-08-03 17:58:55 +0000355}
356
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000357static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000358time_gmtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000359{
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100360 time_t when;
361 struct tm buf, *local;
362
363 if (!parse_time_t_args(args, "|O:gmtime", &when))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100365
366 errno = 0;
367 local = gmtime(&when);
368 if (local == NULL) {
369#ifdef EINVAL
370 if (errno == 0)
371 errno = EINVAL;
372#endif
373 return PyErr_SetFromErrno(PyExc_OSError);
374 }
375 buf = *local;
376 return tmtotuple(&buf);
Guido van Rossum234f9421993-06-17 12:35:49 +0000377}
378
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000379PyDoc_STRVAR(gmtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000380"gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,\n\
Fred Drake193a3f62002-03-12 21:38:49 +0000381 tm_sec, tm_wday, tm_yday, tm_isdst)\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000382\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000383Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400384GMT). When 'seconds' is not passed in, convert the current time instead.\n\
385\n\
386If the platform supports the tm_gmtoff and tm_zone, they are available as\n\
387attributes only.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000388
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100389static int
390pylocaltime(time_t *timep, struct tm *result)
391{
392 struct tm *local;
393
394 assert (timep != NULL);
395 local = localtime(timep);
396 if (local == NULL) {
397 /* unconvertible time */
398#ifdef EINVAL
399 if (errno == 0)
400 errno = EINVAL;
401#endif
402 PyErr_SetFromErrno(PyExc_OSError);
403 return -1;
404 }
405 *result = *local;
406 return 0;
407}
408
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000409static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000410time_localtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000411{
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100412 time_t when;
413 struct tm buf;
414
415 if (!parse_time_t_args(args, "|O:localtime", &when))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 return NULL;
Alexander Belopolskyd9738242012-06-12 16:14:17 -0400417 if (pylocaltime(&when, &buf) == -1)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100418 return NULL;
419 return tmtotuple(&buf);
Guido van Rossum234f9421993-06-17 12:35:49 +0000420}
421
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000422PyDoc_STRVAR(localtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000423"localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 tm_sec,tm_wday,tm_yday,tm_isdst)\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000425\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000426Convert seconds since the Epoch to a time tuple expressing local time.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000427When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000428
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000429/* Convert 9-item tuple to tm structure. Return 1 on success, set
430 * an exception and return 0 on error.
431 */
Guido van Rossum9e90a671993-06-24 11:10:19 +0000432static int
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000433gettmarg(PyObject *args, struct tm *p)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000434{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 int y;
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 memset((void *) p, '\0', sizeof(struct tm));
Guido van Rossumb9081262007-08-25 03:14:09 +0000438
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000439 if (!PyTuple_Check(args)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 PyErr_SetString(PyExc_TypeError,
441 "Tuple or struct_time argument required");
442 return 0;
443 }
Skip Montanaro41cfce92007-08-24 21:11:00 +0000444
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000445 if (!PyArg_ParseTuple(args, "iiiiiiiii",
446 &y, &p->tm_mon, &p->tm_mday,
447 &p->tm_hour, &p->tm_min, &p->tm_sec,
448 &p->tm_wday, &p->tm_yday, &p->tm_isdst))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 p->tm_year = y - 1900;
451 p->tm_mon--;
452 p->tm_wday = (p->tm_wday + 1) % 7;
453 p->tm_yday--;
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400454#ifdef HAVE_STRUCT_TM_TM_ZONE
455 if (Py_TYPE(args) == &StructTimeType) {
456 PyObject *item;
457 item = PyTuple_GET_ITEM(args, 9);
458 p->tm_zone = item == Py_None ? NULL : _PyUnicode_AsString(item);
459 item = PyTuple_GET_ITEM(args, 10);
460 p->tm_gmtoff = item == Py_None ? 0 : PyLong_AsLong(item);
461 if (PyErr_Occurred())
462 return 0;
463 }
464#endif /* HAVE_STRUCT_TM_TM_ZONE */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 return 1;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000466}
467
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000468/* Check values of the struct tm fields before it is passed to strftime() and
469 * asctime(). Return 1 if all values are valid, otherwise set an exception
470 * and returns 0.
471 */
Victor Stinneref128102010-10-07 01:00:52 +0000472static int
473checktm(struct tm* buf)
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000474{
Victor Stinneref128102010-10-07 01:00:52 +0000475 /* Checks added to make sure strftime() and asctime() does not crash Python by
476 indexing blindly into some array for a textual representation
477 by some bad index (fixes bug #897625 and #6608).
478
479 Also support values of zero from Python code for arguments in which
480 that is out of range by forcing that value to the lowest value that
481 is valid (fixed bug #1520914).
482
483 Valid ranges based on what is allowed in struct tm:
484
485 - tm_year: [0, max(int)] (1)
486 - tm_mon: [0, 11] (2)
487 - tm_mday: [1, 31]
488 - tm_hour: [0, 23]
489 - tm_min: [0, 59]
490 - tm_sec: [0, 60]
491 - tm_wday: [0, 6] (1)
492 - tm_yday: [0, 365] (2)
493 - tm_isdst: [-max(int), max(int)]
494
495 (1) gettmarg() handles bounds-checking.
496 (2) Python's acceptable range is one greater than the range in C,
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000497 thus need to check against automatic decrement by gettmarg().
498 */
499 if (buf->tm_mon == -1)
500 buf->tm_mon = 0;
501 else if (buf->tm_mon < 0 || buf->tm_mon > 11) {
502 PyErr_SetString(PyExc_ValueError, "month out of range");
503 return 0;
504 }
505 if (buf->tm_mday == 0)
506 buf->tm_mday = 1;
507 else if (buf->tm_mday < 0 || buf->tm_mday > 31) {
508 PyErr_SetString(PyExc_ValueError, "day of month out of range");
509 return 0;
510 }
511 if (buf->tm_hour < 0 || buf->tm_hour > 23) {
512 PyErr_SetString(PyExc_ValueError, "hour out of range");
513 return 0;
514 }
515 if (buf->tm_min < 0 || buf->tm_min > 59) {
516 PyErr_SetString(PyExc_ValueError, "minute out of range");
517 return 0;
518 }
519 if (buf->tm_sec < 0 || buf->tm_sec > 61) {
520 PyErr_SetString(PyExc_ValueError, "seconds out of range");
521 return 0;
522 }
523 /* tm_wday does not need checking of its upper-bound since taking
524 ``% 7`` in gettmarg() automatically restricts the range. */
525 if (buf->tm_wday < 0) {
526 PyErr_SetString(PyExc_ValueError, "day of week out of range");
527 return 0;
528 }
529 if (buf->tm_yday == -1)
530 buf->tm_yday = 0;
531 else if (buf->tm_yday < 0 || buf->tm_yday > 365) {
532 PyErr_SetString(PyExc_ValueError, "day of year out of range");
533 return 0;
534 }
535 return 1;
536}
537
Victor Stinnerc1f32ca2011-10-14 02:36:13 +0200538#ifdef MS_WINDOWS
539 /* wcsftime() doesn't format correctly time zones, see issue #10653 */
540# undef HAVE_WCSFTIME
541#endif
542
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000543#ifdef HAVE_STRFTIME
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000544#ifdef HAVE_WCSFTIME
545#define time_char wchar_t
546#define format_time wcsftime
547#define time_strlen wcslen
548#else
549#define time_char char
550#define format_time strftime
551#define time_strlen strlen
552#endif
553
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000554static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000555time_strftime(PyObject *self, PyObject *args)
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000556{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 PyObject *tup = NULL;
558 struct tm buf;
559 const time_char *fmt;
Victor Stinnerb2904782010-09-29 10:34:19 +0000560#ifdef HAVE_WCSFTIME
561 wchar_t *format;
562#else
563 PyObject *format;
564#endif
Victor Stinneref128102010-10-07 01:00:52 +0000565 PyObject *format_arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 size_t fmtlen, buflen;
Victor Stinnerb2904782010-09-29 10:34:19 +0000567 time_char *outbuf = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 size_t i;
Victor Stinnerb2904782010-09-29 10:34:19 +0000569 PyObject *ret = NULL;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 memset((void *) &buf, '\0', sizeof(buf));
Guido van Rossum1f41f841998-04-27 19:04:26 +0000572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 /* Will always expect a unicode string to be passed as format.
574 Given that there's no str type anymore in py3k this seems safe.
575 */
Victor Stinneref128102010-10-07 01:00:52 +0000576 if (!PyArg_ParseTuple(args, "U|O:strftime", &format_arg, &tup))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 if (tup == NULL) {
580 time_t tt = time(NULL);
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100581 if (pylocaltime(&tt, &buf) == -1)
582 return NULL;
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000583 }
584 else if (!gettmarg(tup, &buf) || !checktm(&buf))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 return NULL;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000586
Victor Stinner06ec45e2011-01-08 03:35:36 +0000587#if defined(_MSC_VER) || defined(sun)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000588 if (buf.tm_year + 1900 < 1 || 9999 < buf.tm_year + 1900) {
Victor Stinner6f0e4f92011-03-21 02:14:53 +0100589 PyErr_SetString(PyExc_ValueError,
590 "strftime() requires year in [1; 9999]");
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000591 return NULL;
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000592 }
Victor Stinner73ea29c2011-01-08 01:56:31 +0000593#endif
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 /* Normalize tm_isdst just in case someone foolishly implements %Z
596 based on the assumption that tm_isdst falls within the range of
597 [-1, 1] */
598 if (buf.tm_isdst < -1)
599 buf.tm_isdst = -1;
600 else if (buf.tm_isdst > 1)
601 buf.tm_isdst = 1;
Brett Cannond1080a32004-03-02 04:38:10 +0000602
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000603#ifdef HAVE_WCSFTIME
Victor Stinnerbeb4135b2010-10-07 01:02:42 +0000604 format = PyUnicode_AsWideCharString(format_arg, NULL);
Victor Stinnerb2904782010-09-29 10:34:19 +0000605 if (format == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 return NULL;
Victor Stinnerb2904782010-09-29 10:34:19 +0000607 fmt = format;
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000608#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 /* Convert the unicode string to an ascii one */
Victor Stinner1b579672011-12-17 05:47:23 +0100610 format = PyUnicode_EncodeLocale(format_arg, "surrogateescape");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 if (format == NULL)
612 return NULL;
613 fmt = PyBytes_AS_STRING(format);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000614#endif
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000615
Stefan Krah4aea7d32012-02-27 16:30:26 +0100616#if defined(MS_WINDOWS) && !defined(HAVE_WCSFTIME)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 /* check that the format string contains only valid directives */
Victor Stinner5a3ff792011-10-16 19:08:23 +0200618 for(outbuf = strchr(fmt, '%');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 outbuf != NULL;
Victor Stinner5a3ff792011-10-16 19:08:23 +0200620 outbuf = strchr(outbuf+2, '%'))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 {
622 if (outbuf[1]=='#')
623 ++outbuf; /* not documented by python, */
624 if (outbuf[1]=='\0' ||
Victor Stinner5a3ff792011-10-16 19:08:23 +0200625 !strchr("aAbBcdHIjmMpSUwWxXyYzZ%", outbuf[1]))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 {
627 PyErr_SetString(PyExc_ValueError, "Invalid format string");
Stefan Krah4aea7d32012-02-27 16:30:26 +0100628 Py_DECREF(format);
629 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 }
631 }
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000632#endif
633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 fmtlen = time_strlen(fmt);
Guido van Rossumc222ec21999-02-23 00:00:10 +0000635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 /* I hate these functions that presume you know how big the output
637 * will be ahead of time...
638 */
639 for (i = 1024; ; i += i) {
Victor Stinner136ea492011-12-17 22:37:18 +0100640#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100641 int err;
Victor Stinner136ea492011-12-17 22:37:18 +0100642#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char));
644 if (outbuf == NULL) {
Victor Stinnerb2904782010-09-29 10:34:19 +0000645 PyErr_NoMemory();
646 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 }
648 buflen = format_time(outbuf, i, fmt, &buf);
Victor Stinner136ea492011-12-17 22:37:18 +0100649#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100650 err = errno;
Victor Stinner136ea492011-12-17 22:37:18 +0100651#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 if (buflen > 0 || i >= 256 * fmtlen) {
653 /* If the buffer is 256 times as long as the format,
654 it's probably not failing for lack of room!
655 More likely, the format yields an empty result,
656 e.g. an empty format, or %Z when the timezone
657 is unknown. */
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000658#ifdef HAVE_WCSFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 ret = PyUnicode_FromWideChar(outbuf, buflen);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000660#else
Victor Stinner1b579672011-12-17 05:47:23 +0100661 ret = PyUnicode_DecodeLocaleAndSize(outbuf, buflen,
662 "surrogateescape");
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000663#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 PyMem_Free(outbuf);
Victor Stinnerb2904782010-09-29 10:34:19 +0000665 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 }
667 PyMem_Free(outbuf);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000668#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 /* VisualStudio .NET 2005 does this properly */
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100670 if (buflen == 0 && err == EINVAL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 PyErr_SetString(PyExc_ValueError, "Invalid format string");
Victor Stinnerb2904782010-09-29 10:34:19 +0000672 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000674#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 }
Victor Stinnerb2904782010-09-29 10:34:19 +0000676#ifdef HAVE_WCSFTIME
677 PyMem_Free(format);
678#else
679 Py_DECREF(format);
680#endif
681 return ret;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000682}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000683
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000684#undef time_char
685#undef format_time
686
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000687PyDoc_STRVAR(strftime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000688"strftime(format[, tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000689\n\
690Convert a time tuple to a string according to a format specification.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000691See the library reference manual for formatting codes. When the time tuple\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000692is not present, current time as returned by localtime() is used.");
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000693#endif /* HAVE_STRFTIME */
694
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000695static PyObject *
696time_strptime(PyObject *self, PyObject *args)
697{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 PyObject *strptime_module = PyImport_ImportModuleNoBlock("_strptime");
699 PyObject *strptime_result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200700 _Py_IDENTIFIER(_strptime_time);
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 if (!strptime_module)
703 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200704 strptime_result = _PyObject_CallMethodId(strptime_module,
705 &PyId__strptime_time, "O", args);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 Py_DECREF(strptime_module);
707 return strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000708}
709
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000710
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000711PyDoc_STRVAR(strptime_doc,
Brett Cannon20def8b2003-07-01 05:16:08 +0000712"strptime(string, format) -> struct_time\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000713\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000714Parse a string to a time tuple according to a format specification.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000715See the library reference manual for formatting codes (same as strftime()).");
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000716
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000717static PyObject *
718_asctime(struct tm *timeptr)
719{
720 /* Inspired by Open Group reference implementation available at
721 * http://pubs.opengroup.org/onlinepubs/009695399/functions/asctime.html */
Victor Stinner499dfcf2011-03-21 13:26:24 +0100722 static char wday_name[7][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000723 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
724 };
Victor Stinner499dfcf2011-03-21 13:26:24 +0100725 static char mon_name[12][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000726 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
727 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
728 };
Victor Stinner499dfcf2011-03-21 13:26:24 +0100729 return PyUnicode_FromFormat(
730 "%s %s%3d %.2d:%.2d:%.2d %d",
731 wday_name[timeptr->tm_wday],
732 mon_name[timeptr->tm_mon],
733 timeptr->tm_mday, timeptr->tm_hour,
734 timeptr->tm_min, timeptr->tm_sec,
735 1900 + timeptr->tm_year);
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000736}
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000737
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000738static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000739time_asctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000740{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 PyObject *tup = NULL;
742 struct tm buf;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
745 return NULL;
746 if (tup == NULL) {
747 time_t tt = time(NULL);
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100748 if (pylocaltime(&tt, &buf) == -1)
749 return NULL;
750
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000751 } else if (!gettmarg(tup, &buf) || !checktm(&buf))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 return NULL;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000753 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000754}
755
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000756PyDoc_STRVAR(asctime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000757"asctime([tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000758\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000759Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
760When the time tuple is not present, current time as returned by localtime()\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000761is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000762
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000763static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000764time_ctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000765{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 time_t tt;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100767 struct tm buf;
768 if (!parse_time_t_args(args, "|O:ctime", &tt))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100770 if (pylocaltime(&tt, &buf) == -1)
Alexander Belopolsky5da468f2011-01-04 17:15:52 +0000771 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100772 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000773}
774
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000775PyDoc_STRVAR(ctime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000776"ctime(seconds) -> string\n\
777\n\
778Convert a time in seconds since the Epoch to a string in local time.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000779This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000780not present, current time as returned by localtime() is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000781
Guido van Rossum60cd8131998-03-06 17:16:21 +0000782#ifdef HAVE_MKTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000783static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100784time_mktime(PyObject *self, PyObject *tup)
Guido van Rossum234f9421993-06-17 12:35:49 +0000785{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 struct tm buf;
787 time_t tt;
788 if (!gettmarg(tup, &buf))
789 return NULL;
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000790 buf.tm_wday = -1; /* sentinel; original value ignored */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 tt = mktime(&buf);
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000792 /* Return value of -1 does not necessarily mean an error, but tm_wday
Ezio Melotti13925002011-03-16 11:05:33 +0200793 * cannot remain set to -1 if mktime succeeded. */
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000794 if (tt == (time_t)(-1) && buf.tm_wday == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 PyErr_SetString(PyExc_OverflowError,
796 "mktime argument out of range");
797 return NULL;
798 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100799 return PyFloat_FromDouble((double)tt);
Guido van Rossum234f9421993-06-17 12:35:49 +0000800}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000801
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000802PyDoc_STRVAR(mktime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000803"mktime(tuple) -> floating point number\n\
804\n\
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400805Convert a time tuple in local time to seconds since the Epoch.\n\
806Note that mktime(gmtime(0)) will not generally return zero for most\n\
807time zones; instead the returned value will either be equal to that\n\
808of the timezone or altzone attributes on the time module.");
Guido van Rossum60cd8131998-03-06 17:16:21 +0000809#endif /* HAVE_MKTIME */
Guido van Rossum234f9421993-06-17 12:35:49 +0000810
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000811#ifdef HAVE_WORKING_TZSET
Martin v. Löwis1a214512008-06-11 05:26:20 +0000812static void PyInit_timezone(PyObject *module);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000813
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000814static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000815time_tzset(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000816{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 PyObject* m;
Fred Drake9bb74322002-04-01 14:49:59 +0000818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 m = PyImport_ImportModuleNoBlock("time");
820 if (m == NULL) {
821 return NULL;
822 }
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 tzset();
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 /* Reset timezone, altzone, daylight and tzname */
827 PyInit_timezone(m);
828 Py_DECREF(m);
Tim Peters1b6f7a92004-06-20 02:50:16 +0000829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 Py_INCREF(Py_None);
831 return Py_None;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000832}
833
834PyDoc_STRVAR(tzset_doc,
R. David Murray4d55bf92010-12-14 00:55:46 +0000835"tzset()\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000836\n\
837Initialize, or reinitialize, the local timezone to the value stored in\n\
838os.environ['TZ']. The TZ environment variable should be specified in\n\
Neal Norwitzdc8e1942004-07-20 22:34:37 +0000839standard Unix timezone format as documented in the tzset man page\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000840(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
841fall back to UTC. If the TZ environment variable is not set, the local\n\
842timezone is set to the systems best guess of wallclock time.\n\
843Changing the TZ environment variable without calling tzset *may* change\n\
844the local timezone used by methods such as localtime, but this behaviour\n\
845should not be relied on.");
846#endif /* HAVE_WORKING_TZSET */
847
Victor Stinnerec895392012-04-29 02:41:27 +0200848#if defined(MS_WINDOWS) || defined(__APPLE__) \
849 || (defined(HAVE_CLOCK_GETTIME) \
850 && (defined(CLOCK_HIGHRES) || defined(CLOCK_MONOTONIC)))
851#define PYMONOTONIC
852#endif
853
854#ifdef PYMONOTONIC
Victor Stinner071eca32012-03-15 01:17:09 +0100855static PyObject*
Victor Stinnerec895392012-04-29 02:41:27 +0200856pymonotonic(_Py_clock_info_t *info)
Victor Stinnerb94b2662012-01-18 01:50:21 +0100857{
Victor Stinnerec895392012-04-29 02:41:27 +0200858#if defined(MS_WINDOWS)
859 static ULONGLONG (*GetTickCount64) (void) = NULL;
860 static ULONGLONG (CALLBACK *Py_GetTickCount64)(void);
861 static int has_getickcount64 = -1;
862 double result;
863
864 if (has_getickcount64 == -1) {
865 /* GetTickCount64() was added to Windows Vista */
866 if (winver.dwMajorVersion >= 6) {
867 HINSTANCE hKernel32;
868 hKernel32 = GetModuleHandleW(L"KERNEL32");
869 *(FARPROC*)&Py_GetTickCount64 = GetProcAddress(hKernel32,
870 "GetTickCount64");
871 has_getickcount64 = (Py_GetTickCount64 != NULL);
872 }
873 else
874 has_getickcount64 = 0;
875 }
876
877 if (has_getickcount64) {
878 ULONGLONG ticks;
879 ticks = Py_GetTickCount64();
880 result = (double)ticks * 1e-3;
881 }
882 else {
883 static DWORD last_ticks = 0;
884 static DWORD n_overflow = 0;
885 DWORD ticks;
886
887 ticks = GetTickCount();
888 if (ticks < last_ticks)
889 n_overflow++;
890 last_ticks = ticks;
891
892 result = ldexp(n_overflow, 32);
893 result += ticks;
894 result *= 1e-3;
895 }
896
897 if (info) {
898 DWORD timeAdjustment, timeIncrement;
899 BOOL isTimeAdjustmentDisabled, ok;
900 if (has_getickcount64)
901 info->implementation = "GetTickCount64()";
902 else
903 info->implementation = "GetTickCount()";
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400904 info->monotonic = 1;
Victor Stinnerec895392012-04-29 02:41:27 +0200905 ok = GetSystemTimeAdjustment(&timeAdjustment, &timeIncrement,
906 &isTimeAdjustmentDisabled);
907 if (!ok) {
908 PyErr_SetFromWindowsErr(0);
909 return NULL;
910 }
911 info->resolution = timeIncrement * 1e-7;
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200912 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +0200913 }
914 return PyFloat_FromDouble(result);
915
Victor Stinnera8ec5ea2012-03-13 00:25:42 +0100916#elif defined(__APPLE__)
Victor Stinner74eb6c02012-03-28 02:50:46 +0200917 static mach_timebase_info_data_t timebase;
918 uint64_t time;
Victor Stinnera8ec5ea2012-03-13 00:25:42 +0100919 double secs;
920
Victor Stinner74eb6c02012-03-28 02:50:46 +0200921 if (timebase.denom == 0) {
922 /* According to the Technical Q&A QA1398, mach_timebase_info() cannot
923 fail: https://developer.apple.com/library/mac/#qa/qa1398/ */
924 (void)mach_timebase_info(&timebase);
925 }
Victor Stinnera8ec5ea2012-03-13 00:25:42 +0100926
Victor Stinner74eb6c02012-03-28 02:50:46 +0200927 time = mach_absolute_time();
Victor Stinnera8ec5ea2012-03-13 00:25:42 +0100928 secs = (double)time * timebase.numer / timebase.denom * 1e-9;
Victor Stinnerec895392012-04-29 02:41:27 +0200929 if (info) {
930 info->implementation = "mach_absolute_time()";
931 info->resolution = (double)timebase.numer / timebase.denom * 1e-9;
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400932 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200933 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +0200934 }
Victor Stinnera8ec5ea2012-03-13 00:25:42 +0100935 return PyFloat_FromDouble(secs);
Victor Stinnerec895392012-04-29 02:41:27 +0200936
937#elif defined(HAVE_CLOCK_GETTIME) && (defined(CLOCK_HIGHRES) || defined(CLOCK_MONOTONIC))
Victor Stinner8b302012012-02-07 23:29:46 +0100938 struct timespec tp;
Victor Stinnerec895392012-04-29 02:41:27 +0200939#ifdef CLOCK_HIGHRES
940 const clockid_t clk_id = CLOCK_HIGHRES;
941 const char *function = "clock_gettime(CLOCK_HIGHRES)";
942#else
943 const clockid_t clk_id = CLOCK_MONOTONIC;
944 const char *function = "clock_gettime(CLOCK_MONOTONIC)";
945#endif
Victor Stinner8b302012012-02-07 23:29:46 +0100946
Victor Stinnerec895392012-04-29 02:41:27 +0200947 if (clock_gettime(clk_id, &tp) != 0) {
Victor Stinner071eca32012-03-15 01:17:09 +0100948 PyErr_SetFromErrno(PyExc_OSError);
949 return NULL;
950 }
Victor Stinnerec895392012-04-29 02:41:27 +0200951
952 if (info) {
953 struct timespec res;
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400954 info->monotonic = 1;
Victor Stinnerec895392012-04-29 02:41:27 +0200955 info->implementation = function;
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200956 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +0200957 if (clock_getres(clk_id, &res) == 0)
958 info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
959 else
960 info->resolution = 1e-9;
Victor Stinner071eca32012-03-15 01:17:09 +0100961 }
Victor Stinnerec895392012-04-29 02:41:27 +0200962 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinner8b302012012-02-07 23:29:46 +0100963#endif
964}
965
Victor Stinner071eca32012-03-15 01:17:09 +0100966static PyObject *
Victor Stinnerec895392012-04-29 02:41:27 +0200967time_monotonic(PyObject *self, PyObject *unused)
Victor Stinner071eca32012-03-15 01:17:09 +0100968{
Victor Stinnerec895392012-04-29 02:41:27 +0200969 return pymonotonic(NULL);
Victor Stinner071eca32012-03-15 01:17:09 +0100970}
971
Victor Stinnerec895392012-04-29 02:41:27 +0200972PyDoc_STRVAR(monotonic_doc,
973"monotonic() -> float\n\
Victor Stinner8b302012012-02-07 23:29:46 +0100974\n\
Victor Stinnerec895392012-04-29 02:41:27 +0200975Monotonic clock, cannot go backward.");
976#endif /* PYMONOTONIC */
Victor Stinnerec919cc2012-03-15 00:58:32 +0100977
Victor Stinnerec895392012-04-29 02:41:27 +0200978static PyObject*
979perf_counter(_Py_clock_info_t *info)
980{
981#if defined(WIN32_PERF_COUNTER) || defined(PYMONOTONIC)
982 PyObject *res;
983#endif
984#if defined(WIN32_PERF_COUNTER)
985 static int use_perf_counter = 1;
986#endif
987#ifdef PYMONOTONIC
988 static int use_monotonic = 1;
989#endif
990
991#ifdef WIN32_PERF_COUNTER
992 if (use_perf_counter) {
993 if (win_perf_counter(info, &res) == 0)
994 return res;
995 use_perf_counter = 0;
996 }
997#endif
998
999#ifdef PYMONOTONIC
1000 if (use_monotonic) {
1001 res = pymonotonic(info);
1002 if (res != NULL)
1003 return res;
1004 use_monotonic = 0;
1005 PyErr_Clear();
1006 }
1007#endif
1008
1009 return floattime(info);
1010}
1011
1012static PyObject *
1013time_perf_counter(PyObject *self, PyObject *unused)
1014{
1015 return perf_counter(NULL);
1016}
1017
1018PyDoc_STRVAR(perf_counter_doc,
1019"perf_counter() -> float\n\
1020\n\
1021Performance counter for benchmarking.");
1022
1023static PyObject*
1024py_process_time(_Py_clock_info_t *info)
1025{
1026#if defined(MS_WINDOWS)
1027 HANDLE process;
1028 FILETIME creation_time, exit_time, kernel_time, user_time;
1029 ULARGE_INTEGER large;
1030 double total;
1031 BOOL ok;
1032
1033 process = GetCurrentProcess();
1034 ok = GetProcessTimes(process, &creation_time, &exit_time, &kernel_time, &user_time);
1035 if (!ok)
1036 return PyErr_SetFromWindowsErr(0);
1037
1038 large.u.LowPart = kernel_time.dwLowDateTime;
1039 large.u.HighPart = kernel_time.dwHighDateTime;
1040 total = (double)large.QuadPart;
1041 large.u.LowPart = user_time.dwLowDateTime;
1042 large.u.HighPart = user_time.dwHighDateTime;
1043 total += (double)large.QuadPart;
1044 if (info) {
1045 info->implementation = "GetProcessTimes()";
1046 info->resolution = 1e-7;
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001047 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001048 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001049 }
1050 return PyFloat_FromDouble(total * 1e-7);
1051#else
1052
1053#if defined(HAVE_SYS_RESOURCE_H)
1054 struct rusage ru;
1055#endif
1056#ifdef HAVE_TIMES
1057 struct tms t;
1058 static long ticks_per_second = -1;
1059#endif
1060
1061#if defined(HAVE_CLOCK_GETTIME) \
1062 && (defined(CLOCK_PROCESS_CPUTIME_ID) || defined(CLOCK_PROF))
1063 struct timespec tp;
1064#ifdef CLOCK_PROF
1065 const clockid_t clk_id = CLOCK_PROF;
1066 const char *function = "clock_gettime(CLOCK_PROF)";
1067#else
1068 const clockid_t clk_id = CLOCK_PROCESS_CPUTIME_ID;
1069 const char *function = "clock_gettime(CLOCK_PROCESS_CPUTIME_ID)";
1070#endif
1071
1072 if (clock_gettime(clk_id, &tp) == 0) {
1073 if (info) {
1074 struct timespec res;
1075 info->implementation = function;
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001076 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001077 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001078 if (clock_getres(clk_id, &res) == 0)
1079 info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
1080 else
1081 info->resolution = 1e-9;
1082 }
1083 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
1084 }
1085#endif
1086
1087#if defined(HAVE_SYS_RESOURCE_H)
1088 if (getrusage(RUSAGE_SELF, &ru) == 0) {
1089 double total;
1090 total = ru.ru_utime.tv_sec + ru.ru_utime.tv_usec * 1e-6;
1091 total += ru.ru_stime.tv_sec + ru.ru_stime.tv_usec * 1e-6;
1092 if (info) {
1093 info->implementation = "getrusage(RUSAGE_SELF)";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001094 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001095 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001096 info->resolution = 1e-6;
1097 }
1098 return PyFloat_FromDouble(total);
1099 }
1100#endif
1101
1102#ifdef HAVE_TIMES
1103 if (times(&t) != (clock_t)-1) {
1104 double total;
1105
1106 if (ticks_per_second == -1) {
1107#if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
1108 ticks_per_second = sysconf(_SC_CLK_TCK);
1109 if (ticks_per_second < 1)
1110 ticks_per_second = -1;
1111#elif defined(HZ)
1112 ticks_per_second = HZ;
1113#else
1114 ticks_per_second = 60; /* magic fallback value; may be bogus */
1115#endif
1116 }
1117
1118 if (ticks_per_second != -1) {
1119 total = (double)t.tms_utime / ticks_per_second;
1120 total += (double)t.tms_stime / ticks_per_second;
1121 if (info) {
1122 info->implementation = "times()";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001123 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001124 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001125 info->resolution = 1.0 / ticks_per_second;
1126 }
1127 return PyFloat_FromDouble(total);
1128 }
1129 }
1130#endif
1131
1132 return floatclock(info);
1133#endif
1134}
1135
1136static PyObject *
1137time_process_time(PyObject *self, PyObject *unused)
1138{
1139 return py_process_time(NULL);
1140}
1141
1142PyDoc_STRVAR(process_time_doc,
1143"process_time() -> float\n\
1144\n\
1145Process time for profiling: sum of the kernel and user-space CPU time.");
1146
1147
Victor Stinnerec895392012-04-29 02:41:27 +02001148static PyObject *
1149time_get_clock_info(PyObject *self, PyObject *args)
1150{
1151 char *name;
Victor Stinnerec895392012-04-29 02:41:27 +02001152 _Py_clock_info_t info;
Victor Stinnerbda4b882012-06-12 22:11:44 +02001153 PyObject *obj = NULL, *dict, *ns;
Victor Stinnerec895392012-04-29 02:41:27 +02001154
1155 if (!PyArg_ParseTuple(args, "s:get_clock_info", &name))
1156 return NULL;
1157
1158#ifdef Py_DEBUG
1159 info.implementation = NULL;
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001160 info.monotonic = -1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001161 info.adjustable = -1;
Victor Stinnerec895392012-04-29 02:41:27 +02001162 info.resolution = -1.0;
1163#else
1164 info.implementation = "";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001165 info.monotonic = 0;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001166 info.adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001167 info.resolution = 1.0;
1168#endif
1169
1170 if (strcmp(name, "time") == 0)
1171 obj = floattime(&info);
1172#ifdef PYCLOCK
1173 else if (strcmp(name, "clock") == 0)
1174 obj = pyclock(&info);
1175#endif
1176#ifdef PYMONOTONIC
1177 else if (strcmp(name, "monotonic") == 0)
1178 obj = pymonotonic(&info);
1179#endif
1180 else if (strcmp(name, "perf_counter") == 0)
1181 obj = perf_counter(&info);
1182 else if (strcmp(name, "process_time") == 0)
1183 obj = py_process_time(&info);
1184 else {
1185 PyErr_SetString(PyExc_ValueError, "unknown clock");
1186 return NULL;
1187 }
1188 if (obj == NULL)
1189 return NULL;
1190 Py_DECREF(obj);
1191
Victor Stinnerbda4b882012-06-12 22:11:44 +02001192 dict = PyDict_New();
1193 if (dict == NULL)
Victor Stinnerec895392012-04-29 02:41:27 +02001194 return NULL;
1195
1196 assert(info.implementation != NULL);
1197 obj = PyUnicode_FromString(info.implementation);
1198 if (obj == NULL)
1199 goto error;
Victor Stinnerbda4b882012-06-12 22:11:44 +02001200 if (PyDict_SetItemString(dict, "implementation", obj) == -1)
1201 goto error;
1202 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001203
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001204 assert(info.monotonic != -1);
1205 obj = PyBool_FromLong(info.monotonic);
Victor Stinnerec895392012-04-29 02:41:27 +02001206 if (obj == NULL)
1207 goto error;
Victor Stinnerbda4b882012-06-12 22:11:44 +02001208 if (PyDict_SetItemString(dict, "monotonic", obj) == -1)
1209 goto error;
1210 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001211
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001212 assert(info.adjustable != -1);
1213 obj = PyBool_FromLong(info.adjustable);
Victor Stinnerec895392012-04-29 02:41:27 +02001214 if (obj == NULL)
1215 goto error;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001216 if (PyDict_SetItemString(dict, "adjustable", obj) == -1)
Victor Stinnerbda4b882012-06-12 22:11:44 +02001217 goto error;
1218 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001219
1220 assert(info.resolution > 0.0);
1221 assert(info.resolution <= 1.0);
1222 obj = PyFloat_FromDouble(info.resolution);
1223 if (obj == NULL)
1224 goto error;
Victor Stinnerbda4b882012-06-12 22:11:44 +02001225 if (PyDict_SetItemString(dict, "resolution", obj) == -1)
1226 goto error;
1227 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001228
Victor Stinnerbda4b882012-06-12 22:11:44 +02001229 ns = _PyNamespace_New(dict);
1230 Py_DECREF(dict);
1231 return ns;
Victor Stinnerec895392012-04-29 02:41:27 +02001232
1233error:
Victor Stinnerbda4b882012-06-12 22:11:44 +02001234 Py_DECREF(dict);
1235 Py_XDECREF(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001236 return NULL;
1237}
1238
1239PyDoc_STRVAR(get_clock_info_doc,
1240"get_clock_info(name: str) -> dict\n\
1241\n\
1242Get information of the specified clock.");
Victor Stinner8b302012012-02-07 23:29:46 +01001243
Martin v. Löwisd218dc12008-04-07 03:17:54 +00001244static void
Martin v. Löwis1a214512008-06-11 05:26:20 +00001245PyInit_timezone(PyObject *m) {
1246 /* This code moved from PyInit_time wholesale to allow calling it from
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 time_tzset. In the future, some parts of it can be moved back
1248 (for platforms that don't HAVE_WORKING_TZSET, when we know what they
1249 are), and the extraneous calls to tzset(3) should be removed.
1250 I haven't done this yet, as I don't want to change this code as
1251 little as possible when introducing the time.tzset and time.tzsetwall
1252 methods. This should simply be a method of doing the following once,
1253 at the top of this function and removing the call to tzset() from
1254 time_tzset():
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001256 #ifdef HAVE_TZSET
1257 tzset()
1258 #endif
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 And I'm lazy and hate C so nyer.
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001261 */
Guido van Rossum10b164a2001-09-25 13:59:01 +00001262#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 PyObject *otz0, *otz1;
1264 tzset();
Guido van Rossum26452411998-09-28 22:07:11 +00001265#ifdef PYOS_OS2
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001266 PyModule_AddIntConstant(m, "timezone", _timezone);
Guido van Rossum26452411998-09-28 22:07:11 +00001267#else /* !PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 PyModule_AddIntConstant(m, "timezone", timezone);
Guido van Rossum26452411998-09-28 22:07:11 +00001269#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +00001270#ifdef HAVE_ALTZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001271 PyModule_AddIntConstant(m, "altzone", altzone);
Guido van Rossumb6775db1994-08-01 11:34:53 +00001272#else
Guido van Rossum26452411998-09-28 22:07:11 +00001273#ifdef PYOS_OS2
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +00001275#else /* !PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 PyModule_AddIntConstant(m, "altzone", timezone-3600);
Guido van Rossum26452411998-09-28 22:07:11 +00001277#endif /* PYOS_OS2 */
Guido van Rossumb6775db1994-08-01 11:34:53 +00001278#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 PyModule_AddIntConstant(m, "daylight", daylight);
Victor Stinner1b579672011-12-17 05:47:23 +01001280 otz0 = PyUnicode_DecodeLocale(tzname[0], "surrogateescape");
1281 otz1 = PyUnicode_DecodeLocale(tzname[1], "surrogateescape");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 PyModule_AddObject(m, "tzname", Py_BuildValue("(NN)", otz0, otz1));
Guido van Rossum10b164a2001-09-25 13:59:01 +00001283#else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001284#ifdef HAVE_STRUCT_TM_TM_ZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 {
Guido van Rossum234f9421993-06-17 12:35:49 +00001286#define YEAR ((time_t)((365 * 24 + 6) * 3600))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 time_t t;
1288 struct tm *p;
1289 long janzone, julyzone;
1290 char janname[10], julyname[10];
1291 t = (time((time_t *)0) / YEAR) * YEAR;
1292 p = localtime(&t);
1293 janzone = -p->tm_gmtoff;
1294 strncpy(janname, p->tm_zone ? p->tm_zone : " ", 9);
1295 janname[9] = '\0';
1296 t += YEAR/2;
1297 p = localtime(&t);
1298 julyzone = -p->tm_gmtoff;
1299 strncpy(julyname, p->tm_zone ? p->tm_zone : " ", 9);
1300 julyname[9] = '\0';
Guido van Rossum10b164a2001-09-25 13:59:01 +00001301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 if( janzone < julyzone ) {
1303 /* DST is reversed in the southern hemisphere */
1304 PyModule_AddIntConstant(m, "timezone", julyzone);
1305 PyModule_AddIntConstant(m, "altzone", janzone);
1306 PyModule_AddIntConstant(m, "daylight",
1307 janzone != julyzone);
1308 PyModule_AddObject(m, "tzname",
1309 Py_BuildValue("(zz)",
1310 julyname, janname));
1311 } else {
1312 PyModule_AddIntConstant(m, "timezone", janzone);
1313 PyModule_AddIntConstant(m, "altzone", julyzone);
1314 PyModule_AddIntConstant(m, "daylight",
1315 janzone != julyzone);
1316 PyModule_AddObject(m, "tzname",
1317 Py_BuildValue("(zz)",
1318 janname, julyname));
1319 }
1320 }
Guido van Rossume6a4b7b1997-10-08 15:27:56 +00001321#else
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001322#endif /* HAVE_STRUCT_TM_TM_ZONE */
Tim Peters26ae7cd2001-03-20 03:26:49 +00001323#ifdef __CYGWIN__
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 tzset();
1325 PyModule_AddIntConstant(m, "timezone", _timezone);
1326 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
1327 PyModule_AddIntConstant(m, "daylight", _daylight);
1328 PyModule_AddObject(m, "tzname",
1329 Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
Tim Peters26ae7cd2001-03-20 03:26:49 +00001330#endif /* __CYGWIN__ */
Guido van Rossum10b164a2001-09-25 13:59:01 +00001331#endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Victor Stinnere0be4232011-10-25 13:06:09 +02001332
Victor Stinnerec895392012-04-29 02:41:27 +02001333#if defined(HAVE_CLOCK_GETTIME)
Victor Stinnere0be4232011-10-25 13:06:09 +02001334 PyModule_AddIntMacro(m, CLOCK_REALTIME);
Victor Stinnere0be4232011-10-25 13:06:09 +02001335#ifdef CLOCK_MONOTONIC
1336 PyModule_AddIntMacro(m, CLOCK_MONOTONIC);
1337#endif
1338#ifdef CLOCK_MONOTONIC_RAW
1339 PyModule_AddIntMacro(m, CLOCK_MONOTONIC_RAW);
1340#endif
Victor Stinner1470f352012-04-03 00:31:17 +02001341#ifdef CLOCK_HIGHRES
1342 PyModule_AddIntMacro(m, CLOCK_HIGHRES);
1343#endif
Victor Stinnere0be4232011-10-25 13:06:09 +02001344#ifdef CLOCK_PROCESS_CPUTIME_ID
1345 PyModule_AddIntMacro(m, CLOCK_PROCESS_CPUTIME_ID);
1346#endif
1347#ifdef CLOCK_THREAD_CPUTIME_ID
1348 PyModule_AddIntMacro(m, CLOCK_THREAD_CPUTIME_ID);
1349#endif
1350#endif /* HAVE_CLOCK_GETTIME */
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001351}
1352
1353
1354static PyMethodDef time_methods[] = {
Victor Stinner4195b5c2012-02-08 23:03:19 +01001355 {"time", time_time, METH_NOARGS, time_doc},
Victor Stinnerec895392012-04-29 02:41:27 +02001356#ifdef PYCLOCK
Victor Stinner4195b5c2012-02-08 23:03:19 +01001357 {"clock", time_clock, METH_NOARGS, clock_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001358#endif
Victor Stinnere0be4232011-10-25 13:06:09 +02001359#ifdef HAVE_CLOCK_GETTIME
Victor Stinner4195b5c2012-02-08 23:03:19 +01001360 {"clock_gettime", time_clock_gettime, METH_VARARGS, clock_gettime_doc},
Victor Stinner30d79472012-04-03 00:45:07 +02001361 {"clock_settime", time_clock_settime, METH_VARARGS, clock_settime_doc},
Victor Stinner4195b5c2012-02-08 23:03:19 +01001362 {"clock_getres", time_clock_getres, METH_VARARGS, clock_getres_doc},
Victor Stinnere0be4232011-10-25 13:06:09 +02001363#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 {"sleep", time_sleep, METH_VARARGS, sleep_doc},
1365 {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
1366 {"localtime", time_localtime, METH_VARARGS, localtime_doc},
1367 {"asctime", time_asctime, METH_VARARGS, asctime_doc},
1368 {"ctime", time_ctime, METH_VARARGS, ctime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001369#ifdef HAVE_MKTIME
Victor Stinner4195b5c2012-02-08 23:03:19 +01001370 {"mktime", time_mktime, METH_O, mktime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001371#endif
1372#ifdef HAVE_STRFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 {"strftime", time_strftime, METH_VARARGS, strftime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001374#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 {"strptime", time_strptime, METH_VARARGS, strptime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001376#ifdef HAVE_WORKING_TZSET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 {"tzset", time_tzset, METH_NOARGS, tzset_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001378#endif
Victor Stinnerec895392012-04-29 02:41:27 +02001379#ifdef PYMONOTONIC
1380 {"monotonic", time_monotonic, METH_NOARGS, monotonic_doc},
1381#endif
1382 {"process_time", time_process_time, METH_NOARGS, process_time_doc},
1383 {"perf_counter", time_perf_counter, METH_NOARGS, perf_counter_doc},
1384 {"get_clock_info", time_get_clock_info, METH_VARARGS, get_clock_info_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001385 {NULL, NULL} /* sentinel */
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001386};
1387
1388
1389PyDoc_STRVAR(module_doc,
1390"This module provides various functions to manipulate time values.\n\
1391\n\
1392There are two standard representations of time. One is the number\n\
1393of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
1394or a floating point number (to represent fractions of seconds).\n\
1395The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
1396The actual value can be retrieved by calling gmtime(0).\n\
1397\n\
1398The other representation is a tuple of 9 integers giving local time.\n\
1399The tuple items are:\n\
Alexander Belopolsky03163ac2011-05-02 12:20:52 -04001400 year (including century, e.g. 1998)\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001401 month (1-12)\n\
1402 day (1-31)\n\
1403 hours (0-23)\n\
1404 minutes (0-59)\n\
1405 seconds (0-59)\n\
1406 weekday (0-6, Monday is 0)\n\
1407 Julian day (day in the year, 1-366)\n\
1408 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
1409If the DST flag is 0, the time is given in the regular time zone;\n\
1410if it is 1, the time is given in the DST time zone;\n\
1411if it is -1, mktime() should guess based on the date and time.\n\
1412\n\
1413Variables:\n\
1414\n\
1415timezone -- difference in seconds between UTC and local standard time\n\
1416altzone -- difference in seconds between UTC and local DST time\n\
1417daylight -- whether local time should reflect DST\n\
1418tzname -- tuple of (standard time zone name, DST time zone name)\n\
1419\n\
1420Functions:\n\
1421\n\
1422time() -- return current time in seconds since the Epoch as a float\n\
1423clock() -- return CPU time since process start as a float\n\
1424sleep() -- delay for a number of seconds given as a float\n\
1425gmtime() -- convert seconds since Epoch to UTC tuple\n\
1426localtime() -- convert seconds since Epoch to local time tuple\n\
1427asctime() -- convert time tuple to string\n\
1428ctime() -- convert time in seconds to string\n\
1429mktime() -- convert local time tuple to seconds since Epoch\n\
1430strftime() -- convert time tuple to string according to format specification\n\
1431strptime() -- parse string to time tuple according to format specification\n\
1432tzset() -- change the local timezone");
1433
1434
Martin v. Löwis1a214512008-06-11 05:26:20 +00001435
1436static struct PyModuleDef timemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 PyModuleDef_HEAD_INIT,
1438 "time",
1439 module_doc,
1440 -1,
1441 time_methods,
1442 NULL,
1443 NULL,
1444 NULL,
1445 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001446};
1447
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001448PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001449PyInit_time(void)
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001450{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 PyObject *m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 m = PyModule_Create(&timemodule);
1453 if (m == NULL)
1454 return NULL;
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 /* Set, or reset, module variables like time.timezone */
1457 PyInit_timezone(m);
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 if (!initialized) {
1460 PyStructSequence_InitType(&StructTimeType,
1461 &struct_time_type_desc);
Victor Stinnerec895392012-04-29 02:41:27 +02001462
Victor Stinnerec895392012-04-29 02:41:27 +02001463#ifdef MS_WINDOWS
1464 winver.dwOSVersionInfoSize = sizeof(winver);
1465 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
1466 Py_DECREF(m);
1467 PyErr_SetFromWindowsErr(0);
1468 return NULL;
1469 }
1470#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 }
1472 Py_INCREF(&StructTimeType);
Alexander Belopolskyc142bba2012-06-13 22:15:26 -04001473#ifdef HAVE_STRUCT_TM_TM_ZONE
1474 PyModule_AddIntConstant(m, "_STRUCT_TM_ITEMS", 11);
1475#else
1476 PyModule_AddIntConstant(m, "_STRUCT_TM_ITEMS", 9);
1477#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
1479 initialized = 1;
1480 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001481}
1482
Victor Stinner071eca32012-03-15 01:17:09 +01001483static PyObject*
Victor Stinnerec895392012-04-29 02:41:27 +02001484floattime(_Py_clock_info_t *info)
Victor Stinner4195b5c2012-02-08 23:03:19 +01001485{
1486 _PyTime_timeval t;
Victor Stinnerad95c2d2012-03-28 02:54:15 +02001487#ifdef HAVE_CLOCK_GETTIME
1488 struct timespec tp;
1489 int ret;
1490
1491 /* _PyTime_gettimeofday() does not use clock_gettime()
1492 because it would require to link Python to the rt (real-time)
1493 library, at least on Linux */
1494 ret = clock_gettime(CLOCK_REALTIME, &tp);
Victor Stinnerec895392012-04-29 02:41:27 +02001495 if (ret == 0) {
1496 if (info) {
1497 struct timespec res;
1498 info->implementation = "clock_gettime(CLOCK_REALTIME)";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001499 info->monotonic = 0;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001500 info->adjustable = 1;
Victor Stinnerec895392012-04-29 02:41:27 +02001501 if (clock_getres(CLOCK_REALTIME, &res) == 0)
1502 info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
1503 else
1504 info->resolution = 1e-9;
1505 }
Victor Stinnerad95c2d2012-03-28 02:54:15 +02001506 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinnerec895392012-04-29 02:41:27 +02001507 }
Victor Stinnerad95c2d2012-03-28 02:54:15 +02001508#endif
Victor Stinnerec895392012-04-29 02:41:27 +02001509 _PyTime_gettimeofday_info(&t, info);
Victor Stinner70b2e1e2012-03-26 22:08:02 +02001510 return PyFloat_FromDouble((double)t.tv_sec + t.tv_usec * 1e-6);
Victor Stinner4195b5c2012-02-08 23:03:19 +01001511}
1512
1513
Guido van Rossumb6775db1994-08-01 11:34:53 +00001514/* Implement floatsleep() for various platforms.
1515 When interrupted (or when another error occurs), return -1 and
1516 set an exception; else return 0. */
1517
1518static int
Guido van Rossuma320fd31995-03-09 12:14:15 +00001519floatsleep(double secs)
Guido van Rossum426035c1991-02-19 12:27:35 +00001520{
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001521/* XXX Should test for MS_WINDOWS first! */
Skip Montanaroeb33e5a2007-08-17 12:57:41 +00001522#if defined(HAVE_SELECT) && !defined(__EMX__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 struct timeval t;
1524 double frac;
Victor Stinner48b1ce52011-07-01 13:50:09 +02001525 int err;
1526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 frac = fmod(secs, 1.0);
1528 secs = floor(secs);
1529 t.tv_sec = (long)secs;
1530 t.tv_usec = (long)(frac*1000000.0);
1531 Py_BEGIN_ALLOW_THREADS
Victor Stinner48b1ce52011-07-01 13:50:09 +02001532 err = select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t);
1533 Py_END_ALLOW_THREADS
1534 if (err != 0) {
Guido van Rossum09cbb011999-11-08 15:32:27 +00001535#ifdef EINTR
Victor Stinner48b1ce52011-07-01 13:50:09 +02001536 if (errno == EINTR) {
1537 if (PyErr_CheckSignals())
1538 return -1;
1539 }
1540 else
Guido van Rossum09cbb011999-11-08 15:32:27 +00001541#endif
Victor Stinner48b1ce52011-07-01 13:50:09 +02001542 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 PyErr_SetFromErrno(PyExc_IOError);
1544 return -1;
1545 }
1546 }
Martin v. Löwis02af9642002-01-16 11:04:06 +00001547#elif defined(__WATCOMC__) && !defined(__QNX__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 /* XXX Can't interrupt this sleep */
1549 Py_BEGIN_ALLOW_THREADS
1550 delay((int)(secs * 1000 + 0.5)); /* delay() uses milliseconds */
1551 Py_END_ALLOW_THREADS
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001552#elif defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 {
1554 double millisecs = secs * 1000.0;
1555 unsigned long ul_millis;
Tim Peters513a1cd2003-01-19 04:54:58 +00001556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 if (millisecs > (double)ULONG_MAX) {
1558 PyErr_SetString(PyExc_OverflowError,
1559 "sleep length is too large");
1560 return -1;
1561 }
1562 Py_BEGIN_ALLOW_THREADS
1563 /* Allow sleep(0) to maintain win32 semantics, and as decreed
1564 * by Guido, only the main thread can be interrupted.
1565 */
1566 ul_millis = (unsigned long)millisecs;
Antoine Pitrou6dd381e2011-11-21 21:26:56 +01001567 if (ul_millis == 0 || !_PyOS_IsMainThread())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 Sleep(ul_millis);
1569 else {
1570 DWORD rc;
Antoine Pitrou6dd381e2011-11-21 21:26:56 +01001571 HANDLE hInterruptEvent = _PyOS_SigintEvent();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 ResetEvent(hInterruptEvent);
1573 rc = WaitForSingleObject(hInterruptEvent, ul_millis);
1574 if (rc == WAIT_OBJECT_0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001575 Py_BLOCK_THREADS
1576 errno = EINTR;
1577 PyErr_SetFromErrno(PyExc_IOError);
1578 return -1;
1579 }
1580 }
1581 Py_END_ALLOW_THREADS
1582 }
Martin v. Löwis02af9642002-01-16 11:04:06 +00001583#elif defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001584 /* This Sleep *IS* Interruptable by Exceptions */
1585 Py_BEGIN_ALLOW_THREADS
1586 if (DosSleep(secs * 1000) != NO_ERROR) {
1587 Py_BLOCK_THREADS
1588 PyErr_SetFromErrno(PyExc_IOError);
1589 return -1;
1590 }
1591 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001592#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 /* XXX Can't interrupt this sleep */
1594 Py_BEGIN_ALLOW_THREADS
1595 sleep((int)secs);
1596 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001597#endif
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 return 0;
Guido van Rossum80c9d881991-04-16 08:47:51 +00001600}