blob: d0917a40730b813cd2ee7575e8694b9e16507175 [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
Victor Stinnera8ec5ea2012-03-13 00:25:42 +010040#if defined(__APPLE__)
41#include <mach/mach_time.h>
42#endif
43
Guido van Rossum234f9421993-06-17 12:35:49 +000044/* Forward declarations */
Tim Petersdbd9ba62000-07-09 03:09:57 +000045static int floatsleep(double);
Victor Stinnerec895392012-04-29 02:41:27 +020046static PyObject* floattime(_Py_clock_info_t *info);
47
48#ifdef MS_WINDOWS
49static OSVERSIONINFOEX winver;
50#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000051
Barry Warsaw9a2a8a81996-12-06 23:32:14 +000052static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +010053time_time(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000054{
Victor Stinnerec895392012-04-29 02:41:27 +020055 return floattime(NULL);
Guido van Rossumb6775db1994-08-01 11:34:53 +000056}
57
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000058PyDoc_STRVAR(time_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +010059"time() -> floating point number\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +000060\n\
61Return the current time in seconds since the Epoch.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000062Fractions of a second may be present if the system clock provides them.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +000063
Victor Stinner85fdfa82012-01-27 00:38:48 +010064#if defined(HAVE_CLOCK)
65
66#ifndef CLOCKS_PER_SEC
67#ifdef CLK_TCK
68#define CLOCKS_PER_SEC CLK_TCK
69#else
70#define CLOCKS_PER_SEC 1000000
71#endif
72#endif
73
Victor Stinner4195b5c2012-02-08 23:03:19 +010074static PyObject *
Victor Stinnerec895392012-04-29 02:41:27 +020075floatclock(_Py_clock_info_t *info)
Victor Stinner85fdfa82012-01-27 00:38:48 +010076{
Victor Stinner4195b5c2012-02-08 23:03:19 +010077 clock_t value;
78 value = clock();
79 if (value == (clock_t)-1) {
Victor Stinner85fdfa82012-01-27 00:38:48 +010080 PyErr_SetString(PyExc_RuntimeError,
81 "the processor time used is not available "
82 "or its value cannot be represented");
Victor Stinner4195b5c2012-02-08 23:03:19 +010083 return NULL;
Victor Stinner85fdfa82012-01-27 00:38:48 +010084 }
Victor Stinnerec895392012-04-29 02:41:27 +020085 if (info) {
86 info->implementation = "clock()";
87 info->resolution = 1.0 / (double)CLOCKS_PER_SEC;
Benjamin Peterson49a69e42012-05-01 09:38:34 -040088 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +020089 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +020090 }
Victor Stinner4195b5c2012-02-08 23:03:19 +010091 return PyFloat_FromDouble((double)value / CLOCKS_PER_SEC);
Victor Stinner85fdfa82012-01-27 00:38:48 +010092}
93#endif /* HAVE_CLOCK */
94
Thomas Wouters477c8d52006-05-27 19:21:47 +000095#if defined(MS_WINDOWS) && !defined(__BORLANDC__)
Victor Stinnerec895392012-04-29 02:41:27 +020096#define WIN32_PERF_COUNTER
Victor Stinner9122fdd2011-07-04 13:55:40 +020097/* Win32 has better clock replacement; we have our own version, due to Mark
98 Hammond and Tim Peters */
Victor Stinnerec895392012-04-29 02:41:27 +020099static int
100win_perf_counter(_Py_clock_info_t *info, PyObject **result)
Guido van Rossum3917c221997-04-02 05:35:28 +0000101{
Victor Stinner8b302012012-02-07 23:29:46 +0100102 static LONGLONG cpu_frequency = 0;
Victor Stinner4195b5c2012-02-08 23:03:19 +0100103 static LONGLONG ctrStart;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 LARGE_INTEGER now;
Victor Stinner4195b5c2012-02-08 23:03:19 +0100105 double diff;
Guido van Rossum3917c221997-04-02 05:35:28 +0000106
Victor Stinner8b302012012-02-07 23:29:46 +0100107 if (cpu_frequency == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000108 LARGE_INTEGER freq;
Victor Stinner8b302012012-02-07 23:29:46 +0100109 QueryPerformanceCounter(&now);
Victor Stinner4195b5c2012-02-08 23:03:19 +0100110 ctrStart = now.QuadPart;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
112 /* Unlikely to happen - this works on all intel
113 machines at least! Revert to clock() */
Victor Stinnerec895392012-04-29 02:41:27 +0200114 *result = NULL;
115 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000116 }
Victor Stinner8b302012012-02-07 23:29:46 +0100117 cpu_frequency = freq.QuadPart;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000118 }
119 QueryPerformanceCounter(&now);
Victor Stinner4195b5c2012-02-08 23:03:19 +0100120 diff = (double)(now.QuadPart - ctrStart);
Victor Stinnerec895392012-04-29 02:41:27 +0200121 if (info) {
122 info->implementation = "QueryPerformanceCounter()";
123 info->resolution = 1.0 / (double)cpu_frequency;
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400124 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200125 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +0200126 }
127 *result = PyFloat_FromDouble(diff / (double)cpu_frequency);
128 return 0;
Guido van Rossum3917c221997-04-02 05:35:28 +0000129}
Victor Stinner8b302012012-02-07 23:29:46 +0100130#endif
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000131
Victor Stinnerec895392012-04-29 02:41:27 +0200132#if defined(WIN32_PERF_COUNTER) || defined(HAVE_CLOCK)
133#define PYCLOCK
134static PyObject*
135pyclock(_Py_clock_info_t *info)
136{
137#ifdef WIN32_PERF_COUNTER
138 PyObject *res;
139 if (win_perf_counter(info, &res) == 0)
140 return res;
141#endif
142 return floatclock(info);
143}
144
Victor Stinner9122fdd2011-07-04 13:55:40 +0200145static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100146time_clock(PyObject *self, PyObject *unused)
Victor Stinner9122fdd2011-07-04 13:55:40 +0200147{
Victor Stinnerec895392012-04-29 02:41:27 +0200148 return pyclock(NULL);
Victor Stinner9122fdd2011-07-04 13:55:40 +0200149}
Victor Stinner9122fdd2011-07-04 13:55:40 +0200150
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000151PyDoc_STRVAR(clock_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +0100152"clock() -> floating point number\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000153\n\
154Return the CPU time or real time since the start of the process or since\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000155the first call to clock(). This has as much precision as the system\n\
156records.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000157#endif
158
Victor Stinnere0be4232011-10-25 13:06:09 +0200159#ifdef HAVE_CLOCK_GETTIME
160static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100161time_clock_gettime(PyObject *self, PyObject *args)
Victor Stinnere0be4232011-10-25 13:06:09 +0200162{
163 int ret;
Victor Stinnerb8d01692012-04-13 23:44:05 +0200164 int clk_id;
Victor Stinnere0be4232011-10-25 13:06:09 +0200165 struct timespec tp;
166
Victor Stinner4195b5c2012-02-08 23:03:19 +0100167 if (!PyArg_ParseTuple(args, "i:clock_gettime", &clk_id))
Victor Stinnere0be4232011-10-25 13:06:09 +0200168 return NULL;
169
170 ret = clock_gettime((clockid_t)clk_id, &tp);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100171 if (ret != 0) {
Victor Stinnere0be4232011-10-25 13:06:09 +0200172 PyErr_SetFromErrno(PyExc_IOError);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100173 return NULL;
174 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100175 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinnere0be4232011-10-25 13:06:09 +0200176}
177
178PyDoc_STRVAR(clock_gettime_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +0100179"clock_gettime(clk_id) -> floating point number\n\
Victor Stinnere0be4232011-10-25 13:06:09 +0200180\n\
181Return the time of the specified clock clk_id.");
Victor Stinner30d79472012-04-03 00:45:07 +0200182
183static PyObject *
184time_clock_settime(PyObject *self, PyObject *args)
185{
Victor Stinnerb8d01692012-04-13 23:44:05 +0200186 int clk_id;
Victor Stinner30d79472012-04-03 00:45:07 +0200187 PyObject *obj;
Antoine Pitroucf8a1e52013-04-17 22:06:44 +0200188 time_t tv_sec;
189 long tv_nsec;
Victor Stinner30d79472012-04-03 00:45:07 +0200190 struct timespec tp;
191 int ret;
192
193 if (!PyArg_ParseTuple(args, "iO:clock_settime", &clk_id, &obj))
194 return NULL;
195
Victor Stinner3c1b3792014-02-17 00:02:43 +0100196 if (_PyTime_ObjectToTimespec(obj, &tv_sec, &tv_nsec, _PyTime_ROUND_DOWN) == -1)
Victor Stinner30d79472012-04-03 00:45:07 +0200197 return NULL;
Antoine Pitroucf8a1e52013-04-17 22:06:44 +0200198 tp.tv_sec = tv_sec;
199 tp.tv_nsec = tv_nsec;
Victor Stinner30d79472012-04-03 00:45:07 +0200200
201 ret = clock_settime((clockid_t)clk_id, &tp);
202 if (ret != 0) {
203 PyErr_SetFromErrno(PyExc_IOError);
204 return NULL;
205 }
206 Py_RETURN_NONE;
207}
208
209PyDoc_STRVAR(clock_settime_doc,
210"clock_settime(clk_id, time)\n\
211\n\
212Set the time of the specified clock clk_id.");
Victor Stinnere0be4232011-10-25 13:06:09 +0200213
Victor Stinnere0be4232011-10-25 13:06:09 +0200214static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100215time_clock_getres(PyObject *self, PyObject *args)
Victor Stinnere0be4232011-10-25 13:06:09 +0200216{
217 int ret;
Victor Stinnerb8d01692012-04-13 23:44:05 +0200218 int clk_id;
Victor Stinnere0be4232011-10-25 13:06:09 +0200219 struct timespec tp;
220
Victor Stinner4195b5c2012-02-08 23:03:19 +0100221 if (!PyArg_ParseTuple(args, "i:clock_getres", &clk_id))
Victor Stinnere0be4232011-10-25 13:06:09 +0200222 return NULL;
223
224 ret = clock_getres((clockid_t)clk_id, &tp);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100225 if (ret != 0) {
Victor Stinnere0be4232011-10-25 13:06:09 +0200226 PyErr_SetFromErrno(PyExc_IOError);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100227 return NULL;
228 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100229
230 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinnere0be4232011-10-25 13:06:09 +0200231}
232
233PyDoc_STRVAR(clock_getres_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +0100234"clock_getres(clk_id) -> floating point number\n\
Victor Stinnere0be4232011-10-25 13:06:09 +0200235\n\
236Return the resolution (precision) of the specified clock clk_id.");
Victor Stinnerb8d01692012-04-13 23:44:05 +0200237#endif /* HAVE_CLOCK_GETTIME */
Victor Stinnere0be4232011-10-25 13:06:09 +0200238
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000239static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000240time_sleep(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000241{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 double secs;
243 if (!PyArg_ParseTuple(args, "d:sleep", &secs))
244 return NULL;
Victor Stinner7f53a502011-07-05 22:00:25 +0200245 if (secs < 0) {
246 PyErr_SetString(PyExc_ValueError,
247 "sleep length must be non-negative");
248 return NULL;
249 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 if (floatsleep(secs) != 0)
251 return NULL;
252 Py_INCREF(Py_None);
253 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000254}
255
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000256PyDoc_STRVAR(sleep_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000257"sleep(seconds)\n\
258\n\
259Delay execution for a given number of seconds. The argument may be\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000260a floating point number for subsecond precision.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000261
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000262static PyStructSequence_Field struct_time_type_fields[] = {
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000263 {"tm_year", "year, for example, 1993"},
264 {"tm_mon", "month of year, range [1, 12]"},
265 {"tm_mday", "day of month, range [1, 31]"},
266 {"tm_hour", "hours, range [0, 23]"},
267 {"tm_min", "minutes, range [0, 59]"},
268 {"tm_sec", "seconds, range [0, 61])"},
269 {"tm_wday", "day of week, range [0, 6], Monday is 0"},
270 {"tm_yday", "day of year, range [1, 366]"},
271 {"tm_isdst", "1 if summer time is in effect, 0 if not, and -1 if unknown"},
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400272#ifdef HAVE_STRUCT_TM_TM_ZONE
273 {"tm_zone", "abbreviation of timezone name"},
274 {"tm_gmtoff", "offset from UTC in seconds"},
275#endif /* HAVE_STRUCT_TM_TM_ZONE */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000277};
278
279static PyStructSequence_Desc struct_time_type_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 "time.struct_time",
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000281 "The time value as returned by gmtime(), localtime(), and strptime(), and\n"
282 " accepted by asctime(), mktime() and strftime(). May be considered as a\n"
283 " sequence of 9 integers.\n\n"
284 " Note that several fields' values are not the same as those defined by\n"
285 " the C language standard for struct tm. For example, the value of the\n"
286 " field tm_year is the actual year, not year - 1900. See individual\n"
287 " fields' descriptions for details.",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 struct_time_type_fields,
289 9,
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000290};
Tim Peters9ad4b682002-02-13 05:14:18 +0000291
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000292static int initialized;
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000293static PyTypeObject StructTimeType;
294
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400295
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000296static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000297tmtotuple(struct tm *p)
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000298{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 PyObject *v = PyStructSequence_New(&StructTimeType);
300 if (v == NULL)
301 return NULL;
Tim Peters9ad4b682002-02-13 05:14:18 +0000302
Christian Heimes217cfd12007-12-02 14:31:20 +0000303#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val))
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 SET(0, p->tm_year + 1900);
306 SET(1, p->tm_mon + 1); /* Want January == 1 */
307 SET(2, p->tm_mday);
308 SET(3, p->tm_hour);
309 SET(4, p->tm_min);
310 SET(5, p->tm_sec);
311 SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
312 SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
313 SET(8, p->tm_isdst);
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400314#ifdef HAVE_STRUCT_TM_TM_ZONE
315 PyStructSequence_SET_ITEM(v, 9,
316 PyUnicode_DecodeLocale(p->tm_zone, "surrogateescape"));
317 SET(10, p->tm_gmtoff);
318#endif /* HAVE_STRUCT_TM_TM_ZONE */
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000319#undef SET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 if (PyErr_Occurred()) {
321 Py_XDECREF(v);
322 return NULL;
323 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 return v;
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000326}
327
Fred Drakef901abd2004-08-03 17:58:55 +0000328/* Parse arg tuple that can contain an optional float-or-None value;
329 format needs to be "|O:name".
330 Returns non-zero on success (parallels PyArg_ParseTuple).
331*/
332static int
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100333parse_time_t_args(PyObject *args, char *format, time_t *pwhen)
Fred Drakef901abd2004-08-03 17:58:55 +0000334{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 PyObject *ot = NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100336 time_t whent;
Fred Drakef901abd2004-08-03 17:58:55 +0000337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 if (!PyArg_ParseTuple(args, format, &ot))
339 return 0;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100340 if (ot == NULL || ot == Py_None) {
341 whent = time(NULL);
342 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 else {
Victor Stinner3c1b3792014-02-17 00:02:43 +0100344 if (_PyTime_ObjectToTime_t(ot, &whent, _PyTime_ROUND_DOWN) == -1)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100345 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 }
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100347 *pwhen = whent;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 return 1;
Fred Drakef901abd2004-08-03 17:58:55 +0000349}
350
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000351static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000352time_gmtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000353{
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100354 time_t when;
355 struct tm buf, *local;
356
357 if (!parse_time_t_args(args, "|O:gmtime", &when))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100359
360 errno = 0;
361 local = gmtime(&when);
362 if (local == NULL) {
363#ifdef EINVAL
364 if (errno == 0)
365 errno = EINVAL;
366#endif
367 return PyErr_SetFromErrno(PyExc_OSError);
368 }
369 buf = *local;
370 return tmtotuple(&buf);
Guido van Rossum234f9421993-06-17 12:35:49 +0000371}
372
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000373PyDoc_STRVAR(gmtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000374"gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,\n\
Fred Drake193a3f62002-03-12 21:38:49 +0000375 tm_sec, tm_wday, tm_yday, tm_isdst)\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000376\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000377Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400378GMT). When 'seconds' is not passed in, convert the current time instead.\n\
379\n\
380If the platform supports the tm_gmtoff and tm_zone, they are available as\n\
381attributes only.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000382
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100383static int
384pylocaltime(time_t *timep, struct tm *result)
385{
386 struct tm *local;
387
388 assert (timep != NULL);
389 local = localtime(timep);
390 if (local == NULL) {
391 /* unconvertible time */
392#ifdef EINVAL
393 if (errno == 0)
394 errno = EINVAL;
395#endif
396 PyErr_SetFromErrno(PyExc_OSError);
397 return -1;
398 }
399 *result = *local;
400 return 0;
401}
402
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000403static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000404time_localtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000405{
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100406 time_t when;
407 struct tm buf;
408
409 if (!parse_time_t_args(args, "|O:localtime", &when))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 return NULL;
Alexander Belopolskyd9738242012-06-12 16:14:17 -0400411 if (pylocaltime(&when, &buf) == -1)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100412 return NULL;
413 return tmtotuple(&buf);
Guido van Rossum234f9421993-06-17 12:35:49 +0000414}
415
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000416PyDoc_STRVAR(localtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000417"localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 tm_sec,tm_wday,tm_yday,tm_isdst)\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000419\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000420Convert seconds since the Epoch to a time tuple expressing local time.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000421When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000422
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000423/* Convert 9-item tuple to tm structure. Return 1 on success, set
424 * an exception and return 0 on error.
425 */
Guido van Rossum9e90a671993-06-24 11:10:19 +0000426static int
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000427gettmarg(PyObject *args, struct tm *p)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000428{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 int y;
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 memset((void *) p, '\0', sizeof(struct tm));
Guido van Rossumb9081262007-08-25 03:14:09 +0000432
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000433 if (!PyTuple_Check(args)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 PyErr_SetString(PyExc_TypeError,
435 "Tuple or struct_time argument required");
436 return 0;
437 }
Skip Montanaro41cfce92007-08-24 21:11:00 +0000438
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000439 if (!PyArg_ParseTuple(args, "iiiiiiiii",
440 &y, &p->tm_mon, &p->tm_mday,
441 &p->tm_hour, &p->tm_min, &p->tm_sec,
442 &p->tm_wday, &p->tm_yday, &p->tm_isdst))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 p->tm_year = y - 1900;
445 p->tm_mon--;
446 p->tm_wday = (p->tm_wday + 1) % 7;
447 p->tm_yday--;
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400448#ifdef HAVE_STRUCT_TM_TM_ZONE
449 if (Py_TYPE(args) == &StructTimeType) {
450 PyObject *item;
451 item = PyTuple_GET_ITEM(args, 9);
452 p->tm_zone = item == Py_None ? NULL : _PyUnicode_AsString(item);
453 item = PyTuple_GET_ITEM(args, 10);
454 p->tm_gmtoff = item == Py_None ? 0 : PyLong_AsLong(item);
455 if (PyErr_Occurred())
456 return 0;
457 }
458#endif /* HAVE_STRUCT_TM_TM_ZONE */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 return 1;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000460}
461
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000462/* Check values of the struct tm fields before it is passed to strftime() and
463 * asctime(). Return 1 if all values are valid, otherwise set an exception
464 * and returns 0.
465 */
Victor Stinneref128102010-10-07 01:00:52 +0000466static int
467checktm(struct tm* buf)
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000468{
Victor Stinneref128102010-10-07 01:00:52 +0000469 /* Checks added to make sure strftime() and asctime() does not crash Python by
470 indexing blindly into some array for a textual representation
471 by some bad index (fixes bug #897625 and #6608).
472
473 Also support values of zero from Python code for arguments in which
474 that is out of range by forcing that value to the lowest value that
475 is valid (fixed bug #1520914).
476
477 Valid ranges based on what is allowed in struct tm:
478
479 - tm_year: [0, max(int)] (1)
480 - tm_mon: [0, 11] (2)
481 - tm_mday: [1, 31]
482 - tm_hour: [0, 23]
483 - tm_min: [0, 59]
484 - tm_sec: [0, 60]
485 - tm_wday: [0, 6] (1)
486 - tm_yday: [0, 365] (2)
487 - tm_isdst: [-max(int), max(int)]
488
489 (1) gettmarg() handles bounds-checking.
490 (2) Python's acceptable range is one greater than the range in C,
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000491 thus need to check against automatic decrement by gettmarg().
492 */
493 if (buf->tm_mon == -1)
494 buf->tm_mon = 0;
495 else if (buf->tm_mon < 0 || buf->tm_mon > 11) {
496 PyErr_SetString(PyExc_ValueError, "month out of range");
497 return 0;
498 }
499 if (buf->tm_mday == 0)
500 buf->tm_mday = 1;
501 else if (buf->tm_mday < 0 || buf->tm_mday > 31) {
502 PyErr_SetString(PyExc_ValueError, "day of month out of range");
503 return 0;
504 }
505 if (buf->tm_hour < 0 || buf->tm_hour > 23) {
506 PyErr_SetString(PyExc_ValueError, "hour out of range");
507 return 0;
508 }
509 if (buf->tm_min < 0 || buf->tm_min > 59) {
510 PyErr_SetString(PyExc_ValueError, "minute out of range");
511 return 0;
512 }
513 if (buf->tm_sec < 0 || buf->tm_sec > 61) {
514 PyErr_SetString(PyExc_ValueError, "seconds out of range");
515 return 0;
516 }
517 /* tm_wday does not need checking of its upper-bound since taking
518 ``% 7`` in gettmarg() automatically restricts the range. */
519 if (buf->tm_wday < 0) {
520 PyErr_SetString(PyExc_ValueError, "day of week out of range");
521 return 0;
522 }
523 if (buf->tm_yday == -1)
524 buf->tm_yday = 0;
525 else if (buf->tm_yday < 0 || buf->tm_yday > 365) {
526 PyErr_SetString(PyExc_ValueError, "day of year out of range");
527 return 0;
528 }
529 return 1;
530}
531
Victor Stinnerc1f32ca2011-10-14 02:36:13 +0200532#ifdef MS_WINDOWS
533 /* wcsftime() doesn't format correctly time zones, see issue #10653 */
534# undef HAVE_WCSFTIME
535#endif
Alexander Belopolskycf774542012-10-02 18:39:16 -0400536#define STRFTIME_FORMAT_CODES \
537"Commonly used format codes:\n\
538\n\
539%Y Year with century as a decimal number.\n\
540%m Month as a decimal number [01,12].\n\
541%d Day of the month as a decimal number [01,31].\n\
542%H Hour (24-hour clock) as a decimal number [00,23].\n\
543%M Minute as a decimal number [00,59].\n\
544%S Second as a decimal number [00,61].\n\
545%z Time zone offset from UTC.\n\
546%a Locale's abbreviated weekday name.\n\
547%A Locale's full weekday name.\n\
548%b Locale's abbreviated month name.\n\
549%B Locale's full month name.\n\
550%c Locale's appropriate date and time representation.\n\
551%I Hour (12-hour clock) as a decimal number [01,12].\n\
552%p Locale's equivalent of either AM or PM.\n\
553\n\
554Other codes may be available on your platform. See documentation for\n\
555the C library strftime function.\n"
Victor Stinnerc1f32ca2011-10-14 02:36:13 +0200556
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000557#ifdef HAVE_STRFTIME
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000558#ifdef HAVE_WCSFTIME
559#define time_char wchar_t
560#define format_time wcsftime
561#define time_strlen wcslen
562#else
563#define time_char char
564#define format_time strftime
565#define time_strlen strlen
566#endif
567
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000568static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000569time_strftime(PyObject *self, PyObject *args)
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000570{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 PyObject *tup = NULL;
572 struct tm buf;
573 const time_char *fmt;
Victor Stinnerb2904782010-09-29 10:34:19 +0000574#ifdef HAVE_WCSFTIME
575 wchar_t *format;
576#else
577 PyObject *format;
578#endif
Victor Stinneref128102010-10-07 01:00:52 +0000579 PyObject *format_arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 size_t fmtlen, buflen;
Victor Stinnerb2904782010-09-29 10:34:19 +0000581 time_char *outbuf = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 size_t i;
Victor Stinnerb2904782010-09-29 10:34:19 +0000583 PyObject *ret = NULL;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 memset((void *) &buf, '\0', sizeof(buf));
Guido van Rossum1f41f841998-04-27 19:04:26 +0000586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 /* Will always expect a unicode string to be passed as format.
588 Given that there's no str type anymore in py3k this seems safe.
589 */
Victor Stinneref128102010-10-07 01:00:52 +0000590 if (!PyArg_ParseTuple(args, "U|O:strftime", &format_arg, &tup))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 if (tup == NULL) {
594 time_t tt = time(NULL);
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100595 if (pylocaltime(&tt, &buf) == -1)
596 return NULL;
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000597 }
598 else if (!gettmarg(tup, &buf) || !checktm(&buf))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 return NULL;
Guido van Rossum10b164a2001-09-25 13:59:01 +0000600
Victor Stinner36b82d82013-06-25 02:33:53 +0200601#if defined(_MSC_VER) || defined(sun) || defined(_AIX)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000602 if (buf.tm_year + 1900 < 1 || 9999 < buf.tm_year + 1900) {
Victor Stinner6f0e4f92011-03-21 02:14:53 +0100603 PyErr_SetString(PyExc_ValueError,
604 "strftime() requires year in [1; 9999]");
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000605 return NULL;
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000606 }
Victor Stinner73ea29c2011-01-08 01:56:31 +0000607#endif
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 /* Normalize tm_isdst just in case someone foolishly implements %Z
610 based on the assumption that tm_isdst falls within the range of
611 [-1, 1] */
612 if (buf.tm_isdst < -1)
613 buf.tm_isdst = -1;
614 else if (buf.tm_isdst > 1)
615 buf.tm_isdst = 1;
Brett Cannond1080a32004-03-02 04:38:10 +0000616
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000617#ifdef HAVE_WCSFTIME
Victor Stinnerbeb4135b2010-10-07 01:02:42 +0000618 format = PyUnicode_AsWideCharString(format_arg, NULL);
Victor Stinnerb2904782010-09-29 10:34:19 +0000619 if (format == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 return NULL;
Victor Stinnerb2904782010-09-29 10:34:19 +0000621 fmt = format;
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000622#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 /* Convert the unicode string to an ascii one */
Victor Stinner1b579672011-12-17 05:47:23 +0100624 format = PyUnicode_EncodeLocale(format_arg, "surrogateescape");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 if (format == NULL)
626 return NULL;
627 fmt = PyBytes_AS_STRING(format);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000628#endif
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000629
Stefan Krah4aea7d32012-02-27 16:30:26 +0100630#if defined(MS_WINDOWS) && !defined(HAVE_WCSFTIME)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 /* check that the format string contains only valid directives */
Victor Stinner5a3ff792011-10-16 19:08:23 +0200632 for(outbuf = strchr(fmt, '%');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 outbuf != NULL;
Victor Stinner5a3ff792011-10-16 19:08:23 +0200634 outbuf = strchr(outbuf+2, '%'))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 {
636 if (outbuf[1]=='#')
637 ++outbuf; /* not documented by python, */
638 if (outbuf[1]=='\0' ||
Victor Stinner5a3ff792011-10-16 19:08:23 +0200639 !strchr("aAbBcdHIjmMpSUwWxXyYzZ%", outbuf[1]))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 {
641 PyErr_SetString(PyExc_ValueError, "Invalid format string");
Stefan Krah4aea7d32012-02-27 16:30:26 +0100642 Py_DECREF(format);
643 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 }
Tim Golden6e51b8f2013-11-12 12:36:54 +0000645 if ((outbuf[1] == 'y') && buf.tm_year < 0)
646 {
647 PyErr_SetString(PyExc_ValueError,
648 "format %y requires year >= 1900 on Windows");
649 Py_DECREF(format);
650 return NULL;
651 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 }
Victor Stinner93965f72013-11-23 14:59:33 +0100653#elif (defined(_AIX) || defined(sun)) && defined(HAVE_WCSFTIME)
Victor Stinner55329f82013-11-17 23:39:21 +0100654 for(outbuf = wcschr(fmt, '%');
655 outbuf != NULL;
656 outbuf = wcschr(outbuf+2, '%'))
657 {
658 /* Issue #19634: On AIX, wcsftime("y", (1899, 1, 1, 0, 0, 0, 0, 0, 0))
659 returns "0/" instead of "99" */
660 if (outbuf[1] == L'y' && buf.tm_year < 0) {
661 PyErr_SetString(PyExc_ValueError,
662 "format %y requires year >= 1900 on AIX");
Victor Stinner55329f82013-11-17 23:39:21 +0100663 return NULL;
664 }
665 }
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000666#endif
667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 fmtlen = time_strlen(fmt);
Guido van Rossumc222ec21999-02-23 00:00:10 +0000669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 /* I hate these functions that presume you know how big the output
671 * will be ahead of time...
672 */
673 for (i = 1024; ; i += i) {
Victor Stinner136ea492011-12-17 22:37:18 +0100674#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100675 int err;
Victor Stinner136ea492011-12-17 22:37:18 +0100676#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char));
678 if (outbuf == NULL) {
Victor Stinnerb2904782010-09-29 10:34:19 +0000679 PyErr_NoMemory();
680 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 }
682 buflen = format_time(outbuf, i, fmt, &buf);
Victor Stinner136ea492011-12-17 22:37:18 +0100683#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100684 err = errno;
Victor Stinner136ea492011-12-17 22:37:18 +0100685#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 if (buflen > 0 || i >= 256 * fmtlen) {
687 /* If the buffer is 256 times as long as the format,
688 it's probably not failing for lack of room!
689 More likely, the format yields an empty result,
690 e.g. an empty format, or %Z when the timezone
691 is unknown. */
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000692#ifdef HAVE_WCSFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 ret = PyUnicode_FromWideChar(outbuf, buflen);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000694#else
Victor Stinner1b579672011-12-17 05:47:23 +0100695 ret = PyUnicode_DecodeLocaleAndSize(outbuf, buflen,
696 "surrogateescape");
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000697#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 PyMem_Free(outbuf);
Victor Stinnerb2904782010-09-29 10:34:19 +0000699 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 }
701 PyMem_Free(outbuf);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000702#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 /* VisualStudio .NET 2005 does this properly */
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100704 if (buflen == 0 && err == EINVAL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 PyErr_SetString(PyExc_ValueError, "Invalid format string");
Victor Stinnerb2904782010-09-29 10:34:19 +0000706 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000708#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 }
Victor Stinnerb2904782010-09-29 10:34:19 +0000710#ifdef HAVE_WCSFTIME
711 PyMem_Free(format);
712#else
713 Py_DECREF(format);
714#endif
715 return ret;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000716}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000717
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000718#undef time_char
719#undef format_time
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000720PyDoc_STRVAR(strftime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000721"strftime(format[, tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000722\n\
723Convert a time tuple to a string according to a format specification.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000724See the library reference manual for formatting codes. When the time tuple\n\
Alexander Belopolskycf774542012-10-02 18:39:16 -0400725is not present, current time as returned by localtime() is used.\n\
726\n" STRFTIME_FORMAT_CODES);
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000727#endif /* HAVE_STRFTIME */
728
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000729static PyObject *
730time_strptime(PyObject *self, PyObject *args)
731{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 PyObject *strptime_module = PyImport_ImportModuleNoBlock("_strptime");
733 PyObject *strptime_result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200734 _Py_IDENTIFIER(_strptime_time);
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 if (!strptime_module)
737 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200738 strptime_result = _PyObject_CallMethodId(strptime_module,
739 &PyId__strptime_time, "O", args);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 Py_DECREF(strptime_module);
741 return strptime_result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000742}
743
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000744
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000745PyDoc_STRVAR(strptime_doc,
Brett Cannon20def8b2003-07-01 05:16:08 +0000746"strptime(string, format) -> struct_time\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000747\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000748Parse a string to a time tuple according to a format specification.\n\
Alexander Belopolskycf774542012-10-02 18:39:16 -0400749See the library reference manual for formatting codes (same as\n\
750strftime()).\n\
751\n" STRFTIME_FORMAT_CODES);
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000752
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000753static PyObject *
754_asctime(struct tm *timeptr)
755{
756 /* Inspired by Open Group reference implementation available at
757 * http://pubs.opengroup.org/onlinepubs/009695399/functions/asctime.html */
Victor Stinner499dfcf2011-03-21 13:26:24 +0100758 static char wday_name[7][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000759 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
760 };
Victor Stinner499dfcf2011-03-21 13:26:24 +0100761 static char mon_name[12][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000762 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
763 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
764 };
Victor Stinner499dfcf2011-03-21 13:26:24 +0100765 return PyUnicode_FromFormat(
766 "%s %s%3d %.2d:%.2d:%.2d %d",
767 wday_name[timeptr->tm_wday],
768 mon_name[timeptr->tm_mon],
769 timeptr->tm_mday, timeptr->tm_hour,
770 timeptr->tm_min, timeptr->tm_sec,
771 1900 + timeptr->tm_year);
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000772}
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000773
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000774static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000775time_asctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000776{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 PyObject *tup = NULL;
778 struct tm buf;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
781 return NULL;
782 if (tup == NULL) {
783 time_t tt = time(NULL);
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100784 if (pylocaltime(&tt, &buf) == -1)
785 return NULL;
786
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000787 } else if (!gettmarg(tup, &buf) || !checktm(&buf))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 return NULL;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000789 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000790}
791
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000792PyDoc_STRVAR(asctime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000793"asctime([tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000794\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000795Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
796When the time tuple is not present, current time as returned by localtime()\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000797is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000798
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000799static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000800time_ctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000801{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 time_t tt;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100803 struct tm buf;
804 if (!parse_time_t_args(args, "|O:ctime", &tt))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100806 if (pylocaltime(&tt, &buf) == -1)
Alexander Belopolsky5da468f2011-01-04 17:15:52 +0000807 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100808 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000809}
810
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000811PyDoc_STRVAR(ctime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000812"ctime(seconds) -> string\n\
813\n\
814Convert a time in seconds since the Epoch to a string in local time.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000815This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000816not present, current time as returned by localtime() is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000817
Guido van Rossum60cd8131998-03-06 17:16:21 +0000818#ifdef HAVE_MKTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000819static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100820time_mktime(PyObject *self, PyObject *tup)
Guido van Rossum234f9421993-06-17 12:35:49 +0000821{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 struct tm buf;
823 time_t tt;
824 if (!gettmarg(tup, &buf))
825 return NULL;
Victor Stinner1ac42612014-02-21 09:27:17 +0100826#ifdef _AIX
827 /* year < 1902 or year > 2037 */
828 if (buf.tm_year < 2 || buf.tm_year > 137) {
829 /* Issue #19748: On AIX, mktime() doesn't report overflow error for
830 * timestamp < -2^31 or timestamp > 2**31-1. */
831 PyErr_SetString(PyExc_OverflowError,
832 "mktime argument out of range");
833 return NULL;
834 }
835#else
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000836 buf.tm_wday = -1; /* sentinel; original value ignored */
Victor Stinner1ac42612014-02-21 09:27:17 +0100837#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 tt = mktime(&buf);
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000839 /* Return value of -1 does not necessarily mean an error, but tm_wday
Ezio Melotti13925002011-03-16 11:05:33 +0200840 * cannot remain set to -1 if mktime succeeded. */
Victor Stinner93037492013-06-25 22:54:35 +0200841 if (tt == (time_t)(-1)
842#ifndef _AIX
843 /* Return value of -1 does not necessarily mean an error, but
844 * tm_wday cannot remain set to -1 if mktime succeeded. */
845 && buf.tm_wday == -1
846#else
847 /* on AIX, tm_wday is always sets, even on error */
848#endif
849 )
850 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 PyErr_SetString(PyExc_OverflowError,
852 "mktime argument out of range");
853 return NULL;
854 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100855 return PyFloat_FromDouble((double)tt);
Guido van Rossum234f9421993-06-17 12:35:49 +0000856}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000857
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000858PyDoc_STRVAR(mktime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000859"mktime(tuple) -> floating point number\n\
860\n\
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400861Convert a time tuple in local time to seconds since the Epoch.\n\
862Note that mktime(gmtime(0)) will not generally return zero for most\n\
863time zones; instead the returned value will either be equal to that\n\
864of the timezone or altzone attributes on the time module.");
Guido van Rossum60cd8131998-03-06 17:16:21 +0000865#endif /* HAVE_MKTIME */
Guido van Rossum234f9421993-06-17 12:35:49 +0000866
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000867#ifdef HAVE_WORKING_TZSET
Martin v. Löwis1a214512008-06-11 05:26:20 +0000868static void PyInit_timezone(PyObject *module);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000869
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000870static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000871time_tzset(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000872{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 PyObject* m;
Fred Drake9bb74322002-04-01 14:49:59 +0000874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 m = PyImport_ImportModuleNoBlock("time");
876 if (m == NULL) {
877 return NULL;
878 }
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 tzset();
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 /* Reset timezone, altzone, daylight and tzname */
883 PyInit_timezone(m);
884 Py_DECREF(m);
Victor Stinner2ff51b82013-07-17 21:42:45 +0200885 if (PyErr_Occurred())
886 return NULL;
Tim Peters1b6f7a92004-06-20 02:50:16 +0000887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 Py_INCREF(Py_None);
889 return Py_None;
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000890}
891
892PyDoc_STRVAR(tzset_doc,
R. David Murray4d55bf92010-12-14 00:55:46 +0000893"tzset()\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000894\n\
895Initialize, or reinitialize, the local timezone to the value stored in\n\
896os.environ['TZ']. The TZ environment variable should be specified in\n\
Neal Norwitzdc8e1942004-07-20 22:34:37 +0000897standard Unix timezone format as documented in the tzset man page\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000898(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
899fall back to UTC. If the TZ environment variable is not set, the local\n\
900timezone is set to the systems best guess of wallclock time.\n\
901Changing the TZ environment variable without calling tzset *may* change\n\
902the local timezone used by methods such as localtime, but this behaviour\n\
903should not be relied on.");
904#endif /* HAVE_WORKING_TZSET */
905
Victor Stinnerec895392012-04-29 02:41:27 +0200906#if defined(MS_WINDOWS) || defined(__APPLE__) \
907 || (defined(HAVE_CLOCK_GETTIME) \
908 && (defined(CLOCK_HIGHRES) || defined(CLOCK_MONOTONIC)))
909#define PYMONOTONIC
910#endif
911
912#ifdef PYMONOTONIC
Victor Stinner071eca32012-03-15 01:17:09 +0100913static PyObject*
Victor Stinnerec895392012-04-29 02:41:27 +0200914pymonotonic(_Py_clock_info_t *info)
Victor Stinnerb94b2662012-01-18 01:50:21 +0100915{
Victor Stinnerec895392012-04-29 02:41:27 +0200916#if defined(MS_WINDOWS)
917 static ULONGLONG (*GetTickCount64) (void) = NULL;
918 static ULONGLONG (CALLBACK *Py_GetTickCount64)(void);
919 static int has_getickcount64 = -1;
920 double result;
921
922 if (has_getickcount64 == -1) {
923 /* GetTickCount64() was added to Windows Vista */
924 if (winver.dwMajorVersion >= 6) {
925 HINSTANCE hKernel32;
926 hKernel32 = GetModuleHandleW(L"KERNEL32");
927 *(FARPROC*)&Py_GetTickCount64 = GetProcAddress(hKernel32,
928 "GetTickCount64");
929 has_getickcount64 = (Py_GetTickCount64 != NULL);
930 }
931 else
932 has_getickcount64 = 0;
933 }
934
935 if (has_getickcount64) {
936 ULONGLONG ticks;
937 ticks = Py_GetTickCount64();
938 result = (double)ticks * 1e-3;
939 }
940 else {
941 static DWORD last_ticks = 0;
942 static DWORD n_overflow = 0;
943 DWORD ticks;
944
945 ticks = GetTickCount();
946 if (ticks < last_ticks)
947 n_overflow++;
948 last_ticks = ticks;
949
950 result = ldexp(n_overflow, 32);
951 result += ticks;
952 result *= 1e-3;
953 }
954
955 if (info) {
956 DWORD timeAdjustment, timeIncrement;
957 BOOL isTimeAdjustmentDisabled, ok;
958 if (has_getickcount64)
959 info->implementation = "GetTickCount64()";
960 else
961 info->implementation = "GetTickCount()";
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400962 info->monotonic = 1;
Victor Stinnerec895392012-04-29 02:41:27 +0200963 ok = GetSystemTimeAdjustment(&timeAdjustment, &timeIncrement,
964 &isTimeAdjustmentDisabled);
965 if (!ok) {
966 PyErr_SetFromWindowsErr(0);
967 return NULL;
968 }
969 info->resolution = timeIncrement * 1e-7;
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200970 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +0200971 }
972 return PyFloat_FromDouble(result);
973
Victor Stinnera8ec5ea2012-03-13 00:25:42 +0100974#elif defined(__APPLE__)
Victor Stinner74eb6c02012-03-28 02:50:46 +0200975 static mach_timebase_info_data_t timebase;
976 uint64_t time;
Victor Stinnera8ec5ea2012-03-13 00:25:42 +0100977 double secs;
978
Victor Stinner74eb6c02012-03-28 02:50:46 +0200979 if (timebase.denom == 0) {
980 /* According to the Technical Q&A QA1398, mach_timebase_info() cannot
981 fail: https://developer.apple.com/library/mac/#qa/qa1398/ */
982 (void)mach_timebase_info(&timebase);
983 }
Victor Stinnera8ec5ea2012-03-13 00:25:42 +0100984
Victor Stinner74eb6c02012-03-28 02:50:46 +0200985 time = mach_absolute_time();
Victor Stinnera8ec5ea2012-03-13 00:25:42 +0100986 secs = (double)time * timebase.numer / timebase.denom * 1e-9;
Victor Stinnerec895392012-04-29 02:41:27 +0200987 if (info) {
988 info->implementation = "mach_absolute_time()";
989 info->resolution = (double)timebase.numer / timebase.denom * 1e-9;
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400990 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200991 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +0200992 }
Victor Stinnera8ec5ea2012-03-13 00:25:42 +0100993 return PyFloat_FromDouble(secs);
Victor Stinnerec895392012-04-29 02:41:27 +0200994
995#elif defined(HAVE_CLOCK_GETTIME) && (defined(CLOCK_HIGHRES) || defined(CLOCK_MONOTONIC))
Victor Stinner8b302012012-02-07 23:29:46 +0100996 struct timespec tp;
Victor Stinnerec895392012-04-29 02:41:27 +0200997#ifdef CLOCK_HIGHRES
998 const clockid_t clk_id = CLOCK_HIGHRES;
999 const char *function = "clock_gettime(CLOCK_HIGHRES)";
1000#else
1001 const clockid_t clk_id = CLOCK_MONOTONIC;
1002 const char *function = "clock_gettime(CLOCK_MONOTONIC)";
1003#endif
Victor Stinner8b302012012-02-07 23:29:46 +01001004
Victor Stinnerec895392012-04-29 02:41:27 +02001005 if (clock_gettime(clk_id, &tp) != 0) {
Victor Stinner071eca32012-03-15 01:17:09 +01001006 PyErr_SetFromErrno(PyExc_OSError);
1007 return NULL;
1008 }
Victor Stinnerec895392012-04-29 02:41:27 +02001009
1010 if (info) {
1011 struct timespec res;
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001012 info->monotonic = 1;
Victor Stinnerec895392012-04-29 02:41:27 +02001013 info->implementation = function;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001014 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001015 if (clock_getres(clk_id, &res) == 0)
1016 info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
1017 else
1018 info->resolution = 1e-9;
Victor Stinner071eca32012-03-15 01:17:09 +01001019 }
Victor Stinnerec895392012-04-29 02:41:27 +02001020 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinner8b302012012-02-07 23:29:46 +01001021#endif
1022}
1023
Victor Stinner071eca32012-03-15 01:17:09 +01001024static PyObject *
Victor Stinnerec895392012-04-29 02:41:27 +02001025time_monotonic(PyObject *self, PyObject *unused)
Victor Stinner071eca32012-03-15 01:17:09 +01001026{
Victor Stinnerec895392012-04-29 02:41:27 +02001027 return pymonotonic(NULL);
Victor Stinner071eca32012-03-15 01:17:09 +01001028}
1029
Victor Stinnerec895392012-04-29 02:41:27 +02001030PyDoc_STRVAR(monotonic_doc,
1031"monotonic() -> float\n\
Victor Stinner8b302012012-02-07 23:29:46 +01001032\n\
Victor Stinnerec895392012-04-29 02:41:27 +02001033Monotonic clock, cannot go backward.");
1034#endif /* PYMONOTONIC */
Victor Stinnerec919cc2012-03-15 00:58:32 +01001035
Victor Stinnerec895392012-04-29 02:41:27 +02001036static PyObject*
1037perf_counter(_Py_clock_info_t *info)
1038{
1039#if defined(WIN32_PERF_COUNTER) || defined(PYMONOTONIC)
1040 PyObject *res;
1041#endif
1042#if defined(WIN32_PERF_COUNTER)
1043 static int use_perf_counter = 1;
1044#endif
1045#ifdef PYMONOTONIC
1046 static int use_monotonic = 1;
1047#endif
1048
1049#ifdef WIN32_PERF_COUNTER
1050 if (use_perf_counter) {
1051 if (win_perf_counter(info, &res) == 0)
1052 return res;
1053 use_perf_counter = 0;
1054 }
1055#endif
1056
1057#ifdef PYMONOTONIC
1058 if (use_monotonic) {
1059 res = pymonotonic(info);
1060 if (res != NULL)
1061 return res;
1062 use_monotonic = 0;
1063 PyErr_Clear();
1064 }
1065#endif
1066
1067 return floattime(info);
1068}
1069
1070static PyObject *
1071time_perf_counter(PyObject *self, PyObject *unused)
1072{
1073 return perf_counter(NULL);
1074}
1075
1076PyDoc_STRVAR(perf_counter_doc,
1077"perf_counter() -> float\n\
1078\n\
1079Performance counter for benchmarking.");
1080
1081static PyObject*
1082py_process_time(_Py_clock_info_t *info)
1083{
1084#if defined(MS_WINDOWS)
1085 HANDLE process;
1086 FILETIME creation_time, exit_time, kernel_time, user_time;
1087 ULARGE_INTEGER large;
1088 double total;
1089 BOOL ok;
1090
1091 process = GetCurrentProcess();
1092 ok = GetProcessTimes(process, &creation_time, &exit_time, &kernel_time, &user_time);
1093 if (!ok)
1094 return PyErr_SetFromWindowsErr(0);
1095
1096 large.u.LowPart = kernel_time.dwLowDateTime;
1097 large.u.HighPart = kernel_time.dwHighDateTime;
1098 total = (double)large.QuadPart;
1099 large.u.LowPart = user_time.dwLowDateTime;
1100 large.u.HighPart = user_time.dwHighDateTime;
1101 total += (double)large.QuadPart;
1102 if (info) {
1103 info->implementation = "GetProcessTimes()";
1104 info->resolution = 1e-7;
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001105 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001106 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001107 }
1108 return PyFloat_FromDouble(total * 1e-7);
1109#else
1110
1111#if defined(HAVE_SYS_RESOURCE_H)
1112 struct rusage ru;
1113#endif
1114#ifdef HAVE_TIMES
1115 struct tms t;
1116 static long ticks_per_second = -1;
1117#endif
1118
1119#if defined(HAVE_CLOCK_GETTIME) \
1120 && (defined(CLOCK_PROCESS_CPUTIME_ID) || defined(CLOCK_PROF))
1121 struct timespec tp;
1122#ifdef CLOCK_PROF
1123 const clockid_t clk_id = CLOCK_PROF;
1124 const char *function = "clock_gettime(CLOCK_PROF)";
1125#else
1126 const clockid_t clk_id = CLOCK_PROCESS_CPUTIME_ID;
1127 const char *function = "clock_gettime(CLOCK_PROCESS_CPUTIME_ID)";
1128#endif
1129
1130 if (clock_gettime(clk_id, &tp) == 0) {
1131 if (info) {
1132 struct timespec res;
1133 info->implementation = function;
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001134 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001135 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001136 if (clock_getres(clk_id, &res) == 0)
1137 info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
1138 else
1139 info->resolution = 1e-9;
1140 }
1141 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
1142 }
1143#endif
1144
1145#if defined(HAVE_SYS_RESOURCE_H)
1146 if (getrusage(RUSAGE_SELF, &ru) == 0) {
1147 double total;
1148 total = ru.ru_utime.tv_sec + ru.ru_utime.tv_usec * 1e-6;
1149 total += ru.ru_stime.tv_sec + ru.ru_stime.tv_usec * 1e-6;
1150 if (info) {
1151 info->implementation = "getrusage(RUSAGE_SELF)";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001152 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001153 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001154 info->resolution = 1e-6;
1155 }
1156 return PyFloat_FromDouble(total);
1157 }
1158#endif
1159
1160#ifdef HAVE_TIMES
1161 if (times(&t) != (clock_t)-1) {
1162 double total;
1163
1164 if (ticks_per_second == -1) {
1165#if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
1166 ticks_per_second = sysconf(_SC_CLK_TCK);
1167 if (ticks_per_second < 1)
1168 ticks_per_second = -1;
1169#elif defined(HZ)
1170 ticks_per_second = HZ;
1171#else
1172 ticks_per_second = 60; /* magic fallback value; may be bogus */
1173#endif
1174 }
1175
1176 if (ticks_per_second != -1) {
1177 total = (double)t.tms_utime / ticks_per_second;
1178 total += (double)t.tms_stime / ticks_per_second;
1179 if (info) {
1180 info->implementation = "times()";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001181 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001182 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001183 info->resolution = 1.0 / ticks_per_second;
1184 }
1185 return PyFloat_FromDouble(total);
1186 }
1187 }
1188#endif
1189
1190 return floatclock(info);
1191#endif
1192}
1193
1194static PyObject *
1195time_process_time(PyObject *self, PyObject *unused)
1196{
1197 return py_process_time(NULL);
1198}
1199
1200PyDoc_STRVAR(process_time_doc,
1201"process_time() -> float\n\
1202\n\
1203Process time for profiling: sum of the kernel and user-space CPU time.");
1204
1205
Victor Stinnerec895392012-04-29 02:41:27 +02001206static PyObject *
1207time_get_clock_info(PyObject *self, PyObject *args)
1208{
1209 char *name;
Victor Stinnerec895392012-04-29 02:41:27 +02001210 _Py_clock_info_t info;
Victor Stinnerbda4b882012-06-12 22:11:44 +02001211 PyObject *obj = NULL, *dict, *ns;
Victor Stinnerec895392012-04-29 02:41:27 +02001212
1213 if (!PyArg_ParseTuple(args, "s:get_clock_info", &name))
1214 return NULL;
1215
1216#ifdef Py_DEBUG
1217 info.implementation = NULL;
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001218 info.monotonic = -1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001219 info.adjustable = -1;
Victor Stinnerec895392012-04-29 02:41:27 +02001220 info.resolution = -1.0;
1221#else
1222 info.implementation = "";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001223 info.monotonic = 0;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001224 info.adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001225 info.resolution = 1.0;
1226#endif
1227
1228 if (strcmp(name, "time") == 0)
1229 obj = floattime(&info);
1230#ifdef PYCLOCK
1231 else if (strcmp(name, "clock") == 0)
1232 obj = pyclock(&info);
1233#endif
1234#ifdef PYMONOTONIC
1235 else if (strcmp(name, "monotonic") == 0)
1236 obj = pymonotonic(&info);
1237#endif
1238 else if (strcmp(name, "perf_counter") == 0)
1239 obj = perf_counter(&info);
1240 else if (strcmp(name, "process_time") == 0)
1241 obj = py_process_time(&info);
1242 else {
1243 PyErr_SetString(PyExc_ValueError, "unknown clock");
1244 return NULL;
1245 }
1246 if (obj == NULL)
1247 return NULL;
1248 Py_DECREF(obj);
1249
Victor Stinnerbda4b882012-06-12 22:11:44 +02001250 dict = PyDict_New();
1251 if (dict == NULL)
Victor Stinnerec895392012-04-29 02:41:27 +02001252 return NULL;
1253
1254 assert(info.implementation != NULL);
1255 obj = PyUnicode_FromString(info.implementation);
1256 if (obj == NULL)
1257 goto error;
Victor Stinnerbda4b882012-06-12 22:11:44 +02001258 if (PyDict_SetItemString(dict, "implementation", obj) == -1)
1259 goto error;
1260 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001261
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001262 assert(info.monotonic != -1);
1263 obj = PyBool_FromLong(info.monotonic);
Victor Stinnerec895392012-04-29 02:41:27 +02001264 if (obj == NULL)
1265 goto error;
Victor Stinnerbda4b882012-06-12 22:11:44 +02001266 if (PyDict_SetItemString(dict, "monotonic", obj) == -1)
1267 goto error;
1268 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001269
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001270 assert(info.adjustable != -1);
1271 obj = PyBool_FromLong(info.adjustable);
Victor Stinnerec895392012-04-29 02:41:27 +02001272 if (obj == NULL)
1273 goto error;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001274 if (PyDict_SetItemString(dict, "adjustable", obj) == -1)
Victor Stinnerbda4b882012-06-12 22:11:44 +02001275 goto error;
1276 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001277
1278 assert(info.resolution > 0.0);
1279 assert(info.resolution <= 1.0);
1280 obj = PyFloat_FromDouble(info.resolution);
1281 if (obj == NULL)
1282 goto error;
Victor Stinnerbda4b882012-06-12 22:11:44 +02001283 if (PyDict_SetItemString(dict, "resolution", obj) == -1)
1284 goto error;
1285 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001286
Victor Stinnerbda4b882012-06-12 22:11:44 +02001287 ns = _PyNamespace_New(dict);
1288 Py_DECREF(dict);
1289 return ns;
Victor Stinnerec895392012-04-29 02:41:27 +02001290
1291error:
Victor Stinnerbda4b882012-06-12 22:11:44 +02001292 Py_DECREF(dict);
1293 Py_XDECREF(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001294 return NULL;
1295}
1296
1297PyDoc_STRVAR(get_clock_info_doc,
1298"get_clock_info(name: str) -> dict\n\
1299\n\
1300Get information of the specified clock.");
Victor Stinner8b302012012-02-07 23:29:46 +01001301
Martin v. Löwisd218dc12008-04-07 03:17:54 +00001302static void
Martin v. Löwis1a214512008-06-11 05:26:20 +00001303PyInit_timezone(PyObject *m) {
1304 /* This code moved from PyInit_time wholesale to allow calling it from
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 time_tzset. In the future, some parts of it can be moved back
1306 (for platforms that don't HAVE_WORKING_TZSET, when we know what they
1307 are), and the extraneous calls to tzset(3) should be removed.
1308 I haven't done this yet, as I don't want to change this code as
1309 little as possible when introducing the time.tzset and time.tzsetwall
1310 methods. This should simply be a method of doing the following once,
1311 at the top of this function and removing the call to tzset() from
1312 time_tzset():
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 #ifdef HAVE_TZSET
1315 tzset()
1316 #endif
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 And I'm lazy and hate C so nyer.
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001319 */
Guido van Rossum10b164a2001-09-25 13:59:01 +00001320#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 PyObject *otz0, *otz1;
1322 tzset();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 PyModule_AddIntConstant(m, "timezone", timezone);
Guido van Rossumb6775db1994-08-01 11:34:53 +00001324#ifdef HAVE_ALTZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 PyModule_AddIntConstant(m, "altzone", altzone);
Guido van Rossumb6775db1994-08-01 11:34:53 +00001326#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 PyModule_AddIntConstant(m, "altzone", timezone-3600);
Guido van Rossumb6775db1994-08-01 11:34:53 +00001328#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 PyModule_AddIntConstant(m, "daylight", daylight);
Victor Stinner1b579672011-12-17 05:47:23 +01001330 otz0 = PyUnicode_DecodeLocale(tzname[0], "surrogateescape");
1331 otz1 = PyUnicode_DecodeLocale(tzname[1], "surrogateescape");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 PyModule_AddObject(m, "tzname", Py_BuildValue("(NN)", otz0, otz1));
Guido van Rossum10b164a2001-09-25 13:59:01 +00001333#else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001334#ifdef HAVE_STRUCT_TM_TM_ZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 {
Guido van Rossum234f9421993-06-17 12:35:49 +00001336#define YEAR ((time_t)((365 * 24 + 6) * 3600))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 time_t t;
1338 struct tm *p;
1339 long janzone, julyzone;
1340 char janname[10], julyname[10];
1341 t = (time((time_t *)0) / YEAR) * YEAR;
1342 p = localtime(&t);
1343 janzone = -p->tm_gmtoff;
1344 strncpy(janname, p->tm_zone ? p->tm_zone : " ", 9);
1345 janname[9] = '\0';
1346 t += YEAR/2;
1347 p = localtime(&t);
1348 julyzone = -p->tm_gmtoff;
1349 strncpy(julyname, p->tm_zone ? p->tm_zone : " ", 9);
1350 julyname[9] = '\0';
Guido van Rossum10b164a2001-09-25 13:59:01 +00001351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 if( janzone < julyzone ) {
1353 /* DST is reversed in the southern hemisphere */
1354 PyModule_AddIntConstant(m, "timezone", julyzone);
1355 PyModule_AddIntConstant(m, "altzone", janzone);
1356 PyModule_AddIntConstant(m, "daylight",
1357 janzone != julyzone);
1358 PyModule_AddObject(m, "tzname",
1359 Py_BuildValue("(zz)",
1360 julyname, janname));
1361 } else {
1362 PyModule_AddIntConstant(m, "timezone", janzone);
1363 PyModule_AddIntConstant(m, "altzone", julyzone);
1364 PyModule_AddIntConstant(m, "daylight",
1365 janzone != julyzone);
1366 PyModule_AddObject(m, "tzname",
1367 Py_BuildValue("(zz)",
1368 janname, julyname));
1369 }
1370 }
Guido van Rossume6a4b7b1997-10-08 15:27:56 +00001371#else
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001372#endif /* HAVE_STRUCT_TM_TM_ZONE */
Tim Peters26ae7cd2001-03-20 03:26:49 +00001373#ifdef __CYGWIN__
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 tzset();
1375 PyModule_AddIntConstant(m, "timezone", _timezone);
1376 PyModule_AddIntConstant(m, "altzone", _timezone-3600);
1377 PyModule_AddIntConstant(m, "daylight", _daylight);
1378 PyModule_AddObject(m, "tzname",
1379 Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
Tim Peters26ae7cd2001-03-20 03:26:49 +00001380#endif /* __CYGWIN__ */
Guido van Rossum10b164a2001-09-25 13:59:01 +00001381#endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
Victor Stinnere0be4232011-10-25 13:06:09 +02001382
Victor Stinnerec895392012-04-29 02:41:27 +02001383#if defined(HAVE_CLOCK_GETTIME)
Victor Stinnere0be4232011-10-25 13:06:09 +02001384 PyModule_AddIntMacro(m, CLOCK_REALTIME);
Victor Stinnere0be4232011-10-25 13:06:09 +02001385#ifdef CLOCK_MONOTONIC
1386 PyModule_AddIntMacro(m, CLOCK_MONOTONIC);
1387#endif
1388#ifdef CLOCK_MONOTONIC_RAW
1389 PyModule_AddIntMacro(m, CLOCK_MONOTONIC_RAW);
1390#endif
Victor Stinner1470f352012-04-03 00:31:17 +02001391#ifdef CLOCK_HIGHRES
1392 PyModule_AddIntMacro(m, CLOCK_HIGHRES);
1393#endif
Victor Stinnere0be4232011-10-25 13:06:09 +02001394#ifdef CLOCK_PROCESS_CPUTIME_ID
1395 PyModule_AddIntMacro(m, CLOCK_PROCESS_CPUTIME_ID);
1396#endif
1397#ifdef CLOCK_THREAD_CPUTIME_ID
1398 PyModule_AddIntMacro(m, CLOCK_THREAD_CPUTIME_ID);
1399#endif
1400#endif /* HAVE_CLOCK_GETTIME */
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001401}
1402
1403
1404static PyMethodDef time_methods[] = {
Victor Stinner4195b5c2012-02-08 23:03:19 +01001405 {"time", time_time, METH_NOARGS, time_doc},
Victor Stinnerec895392012-04-29 02:41:27 +02001406#ifdef PYCLOCK
Victor Stinner4195b5c2012-02-08 23:03:19 +01001407 {"clock", time_clock, METH_NOARGS, clock_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001408#endif
Victor Stinnere0be4232011-10-25 13:06:09 +02001409#ifdef HAVE_CLOCK_GETTIME
Victor Stinner4195b5c2012-02-08 23:03:19 +01001410 {"clock_gettime", time_clock_gettime, METH_VARARGS, clock_gettime_doc},
Victor Stinner30d79472012-04-03 00:45:07 +02001411 {"clock_settime", time_clock_settime, METH_VARARGS, clock_settime_doc},
Victor Stinner4195b5c2012-02-08 23:03:19 +01001412 {"clock_getres", time_clock_getres, METH_VARARGS, clock_getres_doc},
Victor Stinnere0be4232011-10-25 13:06:09 +02001413#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 {"sleep", time_sleep, METH_VARARGS, sleep_doc},
1415 {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
1416 {"localtime", time_localtime, METH_VARARGS, localtime_doc},
1417 {"asctime", time_asctime, METH_VARARGS, asctime_doc},
1418 {"ctime", time_ctime, METH_VARARGS, ctime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001419#ifdef HAVE_MKTIME
Victor Stinner4195b5c2012-02-08 23:03:19 +01001420 {"mktime", time_mktime, METH_O, mktime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001421#endif
1422#ifdef HAVE_STRFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 {"strftime", time_strftime, METH_VARARGS, strftime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001424#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 {"strptime", time_strptime, METH_VARARGS, strptime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001426#ifdef HAVE_WORKING_TZSET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 {"tzset", time_tzset, METH_NOARGS, tzset_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001428#endif
Victor Stinnerec895392012-04-29 02:41:27 +02001429#ifdef PYMONOTONIC
1430 {"monotonic", time_monotonic, METH_NOARGS, monotonic_doc},
1431#endif
1432 {"process_time", time_process_time, METH_NOARGS, process_time_doc},
1433 {"perf_counter", time_perf_counter, METH_NOARGS, perf_counter_doc},
1434 {"get_clock_info", time_get_clock_info, METH_VARARGS, get_clock_info_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 {NULL, NULL} /* sentinel */
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001436};
1437
1438
1439PyDoc_STRVAR(module_doc,
1440"This module provides various functions to manipulate time values.\n\
1441\n\
1442There are two standard representations of time. One is the number\n\
1443of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
1444or a floating point number (to represent fractions of seconds).\n\
1445The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
1446The actual value can be retrieved by calling gmtime(0).\n\
1447\n\
1448The other representation is a tuple of 9 integers giving local time.\n\
1449The tuple items are:\n\
Alexander Belopolsky03163ac2011-05-02 12:20:52 -04001450 year (including century, e.g. 1998)\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001451 month (1-12)\n\
1452 day (1-31)\n\
1453 hours (0-23)\n\
1454 minutes (0-59)\n\
1455 seconds (0-59)\n\
1456 weekday (0-6, Monday is 0)\n\
1457 Julian day (day in the year, 1-366)\n\
1458 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
1459If the DST flag is 0, the time is given in the regular time zone;\n\
1460if it is 1, the time is given in the DST time zone;\n\
1461if it is -1, mktime() should guess based on the date and time.\n\
1462\n\
1463Variables:\n\
1464\n\
1465timezone -- difference in seconds between UTC and local standard time\n\
1466altzone -- difference in seconds between UTC and local DST time\n\
1467daylight -- whether local time should reflect DST\n\
1468tzname -- tuple of (standard time zone name, DST time zone name)\n\
1469\n\
1470Functions:\n\
1471\n\
1472time() -- return current time in seconds since the Epoch as a float\n\
1473clock() -- return CPU time since process start as a float\n\
1474sleep() -- delay for a number of seconds given as a float\n\
1475gmtime() -- convert seconds since Epoch to UTC tuple\n\
1476localtime() -- convert seconds since Epoch to local time tuple\n\
1477asctime() -- convert time tuple to string\n\
1478ctime() -- convert time in seconds to string\n\
1479mktime() -- convert local time tuple to seconds since Epoch\n\
1480strftime() -- convert time tuple to string according to format specification\n\
1481strptime() -- parse string to time tuple according to format specification\n\
1482tzset() -- change the local timezone");
1483
1484
Martin v. Löwis1a214512008-06-11 05:26:20 +00001485
1486static struct PyModuleDef timemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 PyModuleDef_HEAD_INIT,
1488 "time",
1489 module_doc,
1490 -1,
1491 time_methods,
1492 NULL,
1493 NULL,
1494 NULL,
1495 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001496};
1497
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001498PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001499PyInit_time(void)
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001500{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 PyObject *m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001502 m = PyModule_Create(&timemodule);
1503 if (m == NULL)
1504 return NULL;
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 /* Set, or reset, module variables like time.timezone */
1507 PyInit_timezone(m);
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 if (!initialized) {
Victor Stinner1c8f0592013-07-22 22:24:54 +02001510 if (PyStructSequence_InitType2(&StructTimeType,
1511 &struct_time_type_desc) < 0)
1512 return NULL;
Victor Stinnerec895392012-04-29 02:41:27 +02001513
Victor Stinnerec895392012-04-29 02:41:27 +02001514#ifdef MS_WINDOWS
1515 winver.dwOSVersionInfoSize = sizeof(winver);
1516 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
1517 Py_DECREF(m);
1518 PyErr_SetFromWindowsErr(0);
1519 return NULL;
1520 }
1521#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 }
1523 Py_INCREF(&StructTimeType);
Alexander Belopolskyc142bba2012-06-13 22:15:26 -04001524#ifdef HAVE_STRUCT_TM_TM_ZONE
1525 PyModule_AddIntConstant(m, "_STRUCT_TM_ITEMS", 11);
1526#else
1527 PyModule_AddIntConstant(m, "_STRUCT_TM_ITEMS", 9);
1528#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001529 PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
1530 initialized = 1;
1531 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001532}
1533
Victor Stinner071eca32012-03-15 01:17:09 +01001534static PyObject*
Victor Stinnerec895392012-04-29 02:41:27 +02001535floattime(_Py_clock_info_t *info)
Victor Stinner4195b5c2012-02-08 23:03:19 +01001536{
1537 _PyTime_timeval t;
Victor Stinnerad95c2d2012-03-28 02:54:15 +02001538#ifdef HAVE_CLOCK_GETTIME
1539 struct timespec tp;
1540 int ret;
1541
1542 /* _PyTime_gettimeofday() does not use clock_gettime()
1543 because it would require to link Python to the rt (real-time)
1544 library, at least on Linux */
1545 ret = clock_gettime(CLOCK_REALTIME, &tp);
Victor Stinnerec895392012-04-29 02:41:27 +02001546 if (ret == 0) {
1547 if (info) {
1548 struct timespec res;
1549 info->implementation = "clock_gettime(CLOCK_REALTIME)";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001550 info->monotonic = 0;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001551 info->adjustable = 1;
Victor Stinnerec895392012-04-29 02:41:27 +02001552 if (clock_getres(CLOCK_REALTIME, &res) == 0)
1553 info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
1554 else
1555 info->resolution = 1e-9;
1556 }
Victor Stinnerad95c2d2012-03-28 02:54:15 +02001557 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinnerec895392012-04-29 02:41:27 +02001558 }
Victor Stinnerad95c2d2012-03-28 02:54:15 +02001559#endif
Victor Stinnerec895392012-04-29 02:41:27 +02001560 _PyTime_gettimeofday_info(&t, info);
Victor Stinner70b2e1e2012-03-26 22:08:02 +02001561 return PyFloat_FromDouble((double)t.tv_sec + t.tv_usec * 1e-6);
Victor Stinner4195b5c2012-02-08 23:03:19 +01001562}
1563
1564
Guido van Rossumb6775db1994-08-01 11:34:53 +00001565/* Implement floatsleep() for various platforms.
1566 When interrupted (or when another error occurs), return -1 and
1567 set an exception; else return 0. */
1568
1569static int
Guido van Rossuma320fd31995-03-09 12:14:15 +00001570floatsleep(double secs)
Guido van Rossum426035c1991-02-19 12:27:35 +00001571{
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001572/* XXX Should test for MS_WINDOWS first! */
Skip Montanaroeb33e5a2007-08-17 12:57:41 +00001573#if defined(HAVE_SELECT) && !defined(__EMX__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 struct timeval t;
1575 double frac;
Victor Stinner48b1ce52011-07-01 13:50:09 +02001576 int err;
1577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 frac = fmod(secs, 1.0);
1579 secs = floor(secs);
1580 t.tv_sec = (long)secs;
1581 t.tv_usec = (long)(frac*1000000.0);
1582 Py_BEGIN_ALLOW_THREADS
Victor Stinner48b1ce52011-07-01 13:50:09 +02001583 err = select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t);
1584 Py_END_ALLOW_THREADS
1585 if (err != 0) {
Guido van Rossum09cbb011999-11-08 15:32:27 +00001586#ifdef EINTR
Victor Stinner48b1ce52011-07-01 13:50:09 +02001587 if (errno == EINTR) {
1588 if (PyErr_CheckSignals())
1589 return -1;
1590 }
1591 else
Guido van Rossum09cbb011999-11-08 15:32:27 +00001592#endif
Victor Stinner48b1ce52011-07-01 13:50:09 +02001593 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 PyErr_SetFromErrno(PyExc_IOError);
1595 return -1;
1596 }
1597 }
Martin v. Löwis02af9642002-01-16 11:04:06 +00001598#elif defined(__WATCOMC__) && !defined(__QNX__)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 /* XXX Can't interrupt this sleep */
1600 Py_BEGIN_ALLOW_THREADS
1601 delay((int)(secs * 1000 + 0.5)); /* delay() uses milliseconds */
1602 Py_END_ALLOW_THREADS
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001603#elif defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 {
1605 double millisecs = secs * 1000.0;
1606 unsigned long ul_millis;
Tim Peters513a1cd2003-01-19 04:54:58 +00001607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 if (millisecs > (double)ULONG_MAX) {
1609 PyErr_SetString(PyExc_OverflowError,
1610 "sleep length is too large");
1611 return -1;
1612 }
1613 Py_BEGIN_ALLOW_THREADS
1614 /* Allow sleep(0) to maintain win32 semantics, and as decreed
1615 * by Guido, only the main thread can be interrupted.
1616 */
1617 ul_millis = (unsigned long)millisecs;
Antoine Pitrou6dd381e2011-11-21 21:26:56 +01001618 if (ul_millis == 0 || !_PyOS_IsMainThread())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 Sleep(ul_millis);
1620 else {
1621 DWORD rc;
Antoine Pitrou6dd381e2011-11-21 21:26:56 +01001622 HANDLE hInterruptEvent = _PyOS_SigintEvent();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 ResetEvent(hInterruptEvent);
Martin v. Löwisb26a9b12013-01-25 14:25:48 +01001624 rc = WaitForSingleObjectEx(hInterruptEvent, ul_millis, FALSE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 if (rc == WAIT_OBJECT_0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 Py_BLOCK_THREADS
1627 errno = EINTR;
1628 PyErr_SetFromErrno(PyExc_IOError);
1629 return -1;
1630 }
1631 }
1632 Py_END_ALLOW_THREADS
1633 }
Martin v. Löwis02af9642002-01-16 11:04:06 +00001634#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 /* XXX Can't interrupt this sleep */
1636 Py_BEGIN_ALLOW_THREADS
1637 sleep((int)secs);
1638 Py_END_ALLOW_THREADS
Martin v. Löwis02af9642002-01-16 11:04:06 +00001639#endif
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001641 return 0;
Guido van Rossum80c9d881991-04-16 08:47:51 +00001642}