ยปCore Development>Code coverage>Modules/timemodule.c

Python code coverage for Modules/timemodule.c

#countcontent
1n/a/* Time module */
2n/a
3n/a#include "Python.h"
4n/a
5n/a#include <ctype.h>
6n/a
7n/a#ifdef HAVE_SYS_TIMES_H
8n/a#include <sys/times.h>
9n/a#endif
10n/a
11n/a#ifdef HAVE_SYS_TYPES_H
12n/a#include <sys/types.h>
13n/a#endif
14n/a
15n/a#if defined(HAVE_SYS_RESOURCE_H)
16n/a#include <sys/resource.h>
17n/a#endif
18n/a
19n/a#ifdef QUICKWIN
20n/a#include <io.h>
21n/a#endif
22n/a
23n/a#if defined(__WATCOMC__) && !defined(__QNX__)
24n/a#include <i86.h>
25n/a#else
26n/a#ifdef MS_WINDOWS
27n/a#define WIN32_LEAN_AND_MEAN
28n/a#include <windows.h>
29n/a#include "pythread.h"
30n/a#endif /* MS_WINDOWS */
31n/a#endif /* !__WATCOMC__ || __QNX__ */
32n/a
33n/a/* Forward declarations */
34n/astatic int pysleep(_PyTime_t);
35n/astatic PyObject* floattime(_Py_clock_info_t *info);
36n/a
37n/astatic PyObject *
38n/atime_time(PyObject *self, PyObject *unused)
39n/a{
40n/a return floattime(NULL);
41n/a}
42n/a
43n/aPyDoc_STRVAR(time_doc,
44n/a"time() -> floating point number\n\
45n/a\n\
46n/aReturn the current time in seconds since the Epoch.\n\
47n/aFractions of a second may be present if the system clock provides them.");
48n/a
49n/a#if defined(HAVE_CLOCK)
50n/a
51n/a#ifndef CLOCKS_PER_SEC
52n/a#ifdef CLK_TCK
53n/a#define CLOCKS_PER_SEC CLK_TCK
54n/a#else
55n/a#define CLOCKS_PER_SEC 1000000
56n/a#endif
57n/a#endif
58n/a
59n/astatic PyObject *
60n/afloatclock(_Py_clock_info_t *info)
61n/a{
62n/a clock_t value;
63n/a value = clock();
64n/a if (value == (clock_t)-1) {
65n/a PyErr_SetString(PyExc_RuntimeError,
66n/a "the processor time used is not available "
67n/a "or its value cannot be represented");
68n/a return NULL;
69n/a }
70n/a if (info) {
71n/a info->implementation = "clock()";
72n/a info->resolution = 1.0 / (double)CLOCKS_PER_SEC;
73n/a info->monotonic = 1;
74n/a info->adjustable = 0;
75n/a }
76n/a return PyFloat_FromDouble((double)value / CLOCKS_PER_SEC);
77n/a}
78n/a#endif /* HAVE_CLOCK */
79n/a
80n/a#ifdef MS_WINDOWS
81n/a#define WIN32_PERF_COUNTER
82n/a/* Win32 has better clock replacement; we have our own version, due to Mark
83n/a Hammond and Tim Peters */
84n/astatic PyObject*
85n/awin_perf_counter(_Py_clock_info_t *info)
86n/a{
87n/a static LONGLONG cpu_frequency = 0;
88n/a static LONGLONG ctrStart;
89n/a LARGE_INTEGER now;
90n/a double diff;
91n/a
92n/a if (cpu_frequency == 0) {
93n/a LARGE_INTEGER freq;
94n/a QueryPerformanceCounter(&now);
95n/a ctrStart = now.QuadPart;
96n/a if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
97n/a PyErr_SetFromWindowsErr(0);
98n/a return NULL;
99n/a }
100n/a cpu_frequency = freq.QuadPart;
101n/a }
102n/a QueryPerformanceCounter(&now);
103n/a diff = (double)(now.QuadPart - ctrStart);
104n/a if (info) {
105n/a info->implementation = "QueryPerformanceCounter()";
106n/a info->resolution = 1.0 / (double)cpu_frequency;
107n/a info->monotonic = 1;
108n/a info->adjustable = 0;
109n/a }
110n/a return PyFloat_FromDouble(diff / (double)cpu_frequency);
111n/a}
112n/a#endif /* MS_WINDOWS */
113n/a
114n/a#if defined(WIN32_PERF_COUNTER) || defined(HAVE_CLOCK)
115n/a#define PYCLOCK
116n/astatic PyObject*
117n/apyclock(_Py_clock_info_t *info)
118n/a{
119n/a#ifdef WIN32_PERF_COUNTER
120n/a return win_perf_counter(info);
121n/a#else
122n/a return floatclock(info);
123n/a#endif
124n/a}
125n/a
126n/astatic PyObject *
127n/atime_clock(PyObject *self, PyObject *unused)
128n/a{
129n/a return pyclock(NULL);
130n/a}
131n/a
132n/aPyDoc_STRVAR(clock_doc,
133n/a"clock() -> floating point number\n\
134n/a\n\
135n/aReturn the CPU time or real time since the start of the process or since\n\
136n/athe first call to clock(). This has as much precision as the system\n\
137n/arecords.");
138n/a#endif
139n/a
140n/a#ifdef HAVE_CLOCK_GETTIME
141n/astatic PyObject *
142n/atime_clock_gettime(PyObject *self, PyObject *args)
143n/a{
144n/a int ret;
145n/a int clk_id;
146n/a struct timespec tp;
147n/a
148n/a if (!PyArg_ParseTuple(args, "i:clock_gettime", &clk_id))
149n/a return NULL;
150n/a
151n/a ret = clock_gettime((clockid_t)clk_id, &tp);
152n/a if (ret != 0) {
153n/a PyErr_SetFromErrno(PyExc_OSError);
154n/a return NULL;
155n/a }
156n/a return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
157n/a}
158n/a
159n/aPyDoc_STRVAR(clock_gettime_doc,
160n/a"clock_gettime(clk_id) -> floating point number\n\
161n/a\n\
162n/aReturn the time of the specified clock clk_id.");
163n/a#endif /* HAVE_CLOCK_GETTIME */
164n/a
165n/a#ifdef HAVE_CLOCK_SETTIME
166n/astatic PyObject *
167n/atime_clock_settime(PyObject *self, PyObject *args)
168n/a{
169n/a int clk_id;
170n/a PyObject *obj;
171n/a _PyTime_t t;
172n/a struct timespec tp;
173n/a int ret;
174n/a
175n/a if (!PyArg_ParseTuple(args, "iO:clock_settime", &clk_id, &obj))
176n/a return NULL;
177n/a
178n/a if (_PyTime_FromSecondsObject(&t, obj, _PyTime_ROUND_FLOOR) < 0)
179n/a return NULL;
180n/a
181n/a if (_PyTime_AsTimespec(t, &tp) == -1)
182n/a return NULL;
183n/a
184n/a ret = clock_settime((clockid_t)clk_id, &tp);
185n/a if (ret != 0) {
186n/a PyErr_SetFromErrno(PyExc_OSError);
187n/a return NULL;
188n/a }
189n/a Py_RETURN_NONE;
190n/a}
191n/a
192n/aPyDoc_STRVAR(clock_settime_doc,
193n/a"clock_settime(clk_id, time)\n\
194n/a\n\
195n/aSet the time of the specified clock clk_id.");
196n/a#endif /* HAVE_CLOCK_SETTIME */
197n/a
198n/a#ifdef HAVE_CLOCK_GETRES
199n/astatic PyObject *
200n/atime_clock_getres(PyObject *self, PyObject *args)
201n/a{
202n/a int ret;
203n/a int clk_id;
204n/a struct timespec tp;
205n/a
206n/a if (!PyArg_ParseTuple(args, "i:clock_getres", &clk_id))
207n/a return NULL;
208n/a
209n/a ret = clock_getres((clockid_t)clk_id, &tp);
210n/a if (ret != 0) {
211n/a PyErr_SetFromErrno(PyExc_OSError);
212n/a return NULL;
213n/a }
214n/a
215n/a return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
216n/a}
217n/a
218n/aPyDoc_STRVAR(clock_getres_doc,
219n/a"clock_getres(clk_id) -> floating point number\n\
220n/a\n\
221n/aReturn the resolution (precision) of the specified clock clk_id.");
222n/a#endif /* HAVE_CLOCK_GETRES */
223n/a
224n/astatic PyObject *
225n/atime_sleep(PyObject *self, PyObject *obj)
226n/a{
227n/a _PyTime_t secs;
228n/a if (_PyTime_FromSecondsObject(&secs, obj, _PyTime_ROUND_CEILING))
229n/a return NULL;
230n/a if (secs < 0) {
231n/a PyErr_SetString(PyExc_ValueError,
232n/a "sleep length must be non-negative");
233n/a return NULL;
234n/a }
235n/a if (pysleep(secs) != 0)
236n/a return NULL;
237n/a Py_RETURN_NONE;
238n/a}
239n/a
240n/aPyDoc_STRVAR(sleep_doc,
241n/a"sleep(seconds)\n\
242n/a\n\
243n/aDelay execution for a given number of seconds. The argument may be\n\
244n/aa floating point number for subsecond precision.");
245n/a
246n/astatic PyStructSequence_Field struct_time_type_fields[] = {
247n/a {"tm_year", "year, for example, 1993"},
248n/a {"tm_mon", "month of year, range [1, 12]"},
249n/a {"tm_mday", "day of month, range [1, 31]"},
250n/a {"tm_hour", "hours, range [0, 23]"},
251n/a {"tm_min", "minutes, range [0, 59]"},
252n/a {"tm_sec", "seconds, range [0, 61])"},
253n/a {"tm_wday", "day of week, range [0, 6], Monday is 0"},
254n/a {"tm_yday", "day of year, range [1, 366]"},
255n/a {"tm_isdst", "1 if summer time is in effect, 0 if not, and -1 if unknown"},
256n/a {"tm_zone", "abbreviation of timezone name"},
257n/a {"tm_gmtoff", "offset from UTC in seconds"},
258n/a {0}
259n/a};
260n/a
261n/astatic PyStructSequence_Desc struct_time_type_desc = {
262n/a "time.struct_time",
263n/a "The time value as returned by gmtime(), localtime(), and strptime(), and\n"
264n/a " accepted by asctime(), mktime() and strftime(). May be considered as a\n"
265n/a " sequence of 9 integers.\n\n"
266n/a " Note that several fields' values are not the same as those defined by\n"
267n/a " the C language standard for struct tm. For example, the value of the\n"
268n/a " field tm_year is the actual year, not year - 1900. See individual\n"
269n/a " fields' descriptions for details.",
270n/a struct_time_type_fields,
271n/a 9,
272n/a};
273n/a
274n/astatic int initialized;
275n/astatic PyTypeObject StructTimeType;
276n/a
277n/a
278n/astatic PyObject *
279n/atmtotuple(struct tm *p
280n/a#ifndef HAVE_STRUCT_TM_TM_ZONE
281n/a , const char *zone, int gmtoff
282n/a#endif
283n/a)
284n/a{
285n/a PyObject *v = PyStructSequence_New(&StructTimeType);
286n/a if (v == NULL)
287n/a return NULL;
288n/a
289n/a#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val))
290n/a
291n/a SET(0, p->tm_year + 1900);
292n/a SET(1, p->tm_mon + 1); /* Want January == 1 */
293n/a SET(2, p->tm_mday);
294n/a SET(3, p->tm_hour);
295n/a SET(4, p->tm_min);
296n/a SET(5, p->tm_sec);
297n/a SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
298n/a SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
299n/a SET(8, p->tm_isdst);
300n/a#ifdef HAVE_STRUCT_TM_TM_ZONE
301n/a PyStructSequence_SET_ITEM(v, 9,
302n/a PyUnicode_DecodeLocale(p->tm_zone, "surrogateescape"));
303n/a SET(10, p->tm_gmtoff);
304n/a#else
305n/a PyStructSequence_SET_ITEM(v, 9,
306n/a PyUnicode_DecodeLocale(zone, "surrogateescape"));
307n/a SET(10, gmtoff);
308n/a#endif /* HAVE_STRUCT_TM_TM_ZONE */
309n/a#undef SET
310n/a if (PyErr_Occurred()) {
311n/a Py_XDECREF(v);
312n/a return NULL;
313n/a }
314n/a
315n/a return v;
316n/a}
317n/a
318n/a/* Parse arg tuple that can contain an optional float-or-None value;
319n/a format needs to be "|O:name".
320n/a Returns non-zero on success (parallels PyArg_ParseTuple).
321n/a*/
322n/astatic int
323n/aparse_time_t_args(PyObject *args, const char *format, time_t *pwhen)
324n/a{
325n/a PyObject *ot = NULL;
326n/a time_t whent;
327n/a
328n/a if (!PyArg_ParseTuple(args, format, &ot))
329n/a return 0;
330n/a if (ot == NULL || ot == Py_None) {
331n/a whent = time(NULL);
332n/a }
333n/a else {
334n/a if (_PyTime_ObjectToTime_t(ot, &whent, _PyTime_ROUND_FLOOR) == -1)
335n/a return 0;
336n/a }
337n/a *pwhen = whent;
338n/a return 1;
339n/a}
340n/a
341n/astatic PyObject *
342n/atime_gmtime(PyObject *self, PyObject *args)
343n/a{
344n/a time_t when;
345n/a struct tm buf;
346n/a
347n/a if (!parse_time_t_args(args, "|O:gmtime", &when))
348n/a return NULL;
349n/a
350n/a errno = 0;
351n/a if (_PyTime_gmtime(when, &buf) != 0)
352n/a return NULL;
353n/a#ifdef HAVE_STRUCT_TM_TM_ZONE
354n/a return tmtotuple(&buf);
355n/a#else
356n/a return tmtotuple(&buf, "UTC", 0);
357n/a#endif
358n/a}
359n/a
360n/a#ifndef HAVE_TIMEGM
361n/astatic time_t
362n/atimegm(struct tm *p)
363n/a{
364n/a /* XXX: the following implementation will not work for tm_year < 1970.
365n/a but it is likely that platforms that don't have timegm do not support
366n/a negative timestamps anyways. */
367n/a return p->tm_sec + p->tm_min*60 + p->tm_hour*3600 + p->tm_yday*86400 +
368n/a (p->tm_year-70)*31536000 + ((p->tm_year-69)/4)*86400 -
369n/a ((p->tm_year-1)/100)*86400 + ((p->tm_year+299)/400)*86400;
370n/a}
371n/a#endif
372n/a
373n/aPyDoc_STRVAR(gmtime_doc,
374n/a"gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,\n\
375n/a tm_sec, tm_wday, tm_yday, tm_isdst)\n\
376n/a\n\
377n/aConvert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
378n/aGMT). When 'seconds' is not passed in, convert the current time instead.\n\
379n/a\n\
380n/aIf the platform supports the tm_gmtoff and tm_zone, they are available as\n\
381n/aattributes only.");
382n/a
383n/astatic PyObject *
384n/atime_localtime(PyObject *self, PyObject *args)
385n/a{
386n/a time_t when;
387n/a struct tm buf;
388n/a
389n/a if (!parse_time_t_args(args, "|O:localtime", &when))
390n/a return NULL;
391n/a if (_PyTime_localtime(when, &buf) != 0)
392n/a return NULL;
393n/a#ifdef HAVE_STRUCT_TM_TM_ZONE
394n/a return tmtotuple(&buf);
395n/a#else
396n/a {
397n/a struct tm local = buf;
398n/a char zone[100];
399n/a int gmtoff;
400n/a strftime(zone, sizeof(zone), "%Z", &buf);
401n/a gmtoff = timegm(&buf) - when;
402n/a return tmtotuple(&local, zone, gmtoff);
403n/a }
404n/a#endif
405n/a}
406n/a
407n/aPyDoc_STRVAR(localtime_doc,
408n/a"localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\
409n/a tm_sec,tm_wday,tm_yday,tm_isdst)\n\
410n/a\n\
411n/aConvert seconds since the Epoch to a time tuple expressing local time.\n\
412n/aWhen 'seconds' is not passed in, convert the current time instead.");
413n/a
414n/a/* Convert 9-item tuple to tm structure. Return 1 on success, set
415n/a * an exception and return 0 on error.
416n/a */
417n/astatic int
418n/agettmarg(PyObject *args, struct tm *p)
419n/a{
420n/a int y;
421n/a
422n/a memset((void *) p, '\0', sizeof(struct tm));
423n/a
424n/a if (!PyTuple_Check(args)) {
425n/a PyErr_SetString(PyExc_TypeError,
426n/a "Tuple or struct_time argument required");
427n/a return 0;
428n/a }
429n/a
430n/a if (!PyArg_ParseTuple(args, "iiiiiiiii",
431n/a &y, &p->tm_mon, &p->tm_mday,
432n/a &p->tm_hour, &p->tm_min, &p->tm_sec,
433n/a &p->tm_wday, &p->tm_yday, &p->tm_isdst))
434n/a return 0;
435n/a p->tm_year = y - 1900;
436n/a p->tm_mon--;
437n/a p->tm_wday = (p->tm_wday + 1) % 7;
438n/a p->tm_yday--;
439n/a#ifdef HAVE_STRUCT_TM_TM_ZONE
440n/a if (Py_TYPE(args) == &StructTimeType) {
441n/a PyObject *item;
442n/a item = PyTuple_GET_ITEM(args, 9);
443n/a p->tm_zone = item == Py_None ? NULL : PyUnicode_AsUTF8(item);
444n/a item = PyTuple_GET_ITEM(args, 10);
445n/a p->tm_gmtoff = item == Py_None ? 0 : PyLong_AsLong(item);
446n/a if (PyErr_Occurred())
447n/a return 0;
448n/a }
449n/a#endif /* HAVE_STRUCT_TM_TM_ZONE */
450n/a return 1;
451n/a}
452n/a
453n/a/* Check values of the struct tm fields before it is passed to strftime() and
454n/a * asctime(). Return 1 if all values are valid, otherwise set an exception
455n/a * and returns 0.
456n/a */
457n/astatic int
458n/achecktm(struct tm* buf)
459n/a{
460n/a /* Checks added to make sure strftime() and asctime() does not crash Python by
461n/a indexing blindly into some array for a textual representation
462n/a by some bad index (fixes bug #897625 and #6608).
463n/a
464n/a Also support values of zero from Python code for arguments in which
465n/a that is out of range by forcing that value to the lowest value that
466n/a is valid (fixed bug #1520914).
467n/a
468n/a Valid ranges based on what is allowed in struct tm:
469n/a
470n/a - tm_year: [0, max(int)] (1)
471n/a - tm_mon: [0, 11] (2)
472n/a - tm_mday: [1, 31]
473n/a - tm_hour: [0, 23]
474n/a - tm_min: [0, 59]
475n/a - tm_sec: [0, 60]
476n/a - tm_wday: [0, 6] (1)
477n/a - tm_yday: [0, 365] (2)
478n/a - tm_isdst: [-max(int), max(int)]
479n/a
480n/a (1) gettmarg() handles bounds-checking.
481n/a (2) Python's acceptable range is one greater than the range in C,
482n/a thus need to check against automatic decrement by gettmarg().
483n/a */
484n/a if (buf->tm_mon == -1)
485n/a buf->tm_mon = 0;
486n/a else if (buf->tm_mon < 0 || buf->tm_mon > 11) {
487n/a PyErr_SetString(PyExc_ValueError, "month out of range");
488n/a return 0;
489n/a }
490n/a if (buf->tm_mday == 0)
491n/a buf->tm_mday = 1;
492n/a else if (buf->tm_mday < 0 || buf->tm_mday > 31) {
493n/a PyErr_SetString(PyExc_ValueError, "day of month out of range");
494n/a return 0;
495n/a }
496n/a if (buf->tm_hour < 0 || buf->tm_hour > 23) {
497n/a PyErr_SetString(PyExc_ValueError, "hour out of range");
498n/a return 0;
499n/a }
500n/a if (buf->tm_min < 0 || buf->tm_min > 59) {
501n/a PyErr_SetString(PyExc_ValueError, "minute out of range");
502n/a return 0;
503n/a }
504n/a if (buf->tm_sec < 0 || buf->tm_sec > 61) {
505n/a PyErr_SetString(PyExc_ValueError, "seconds out of range");
506n/a return 0;
507n/a }
508n/a /* tm_wday does not need checking of its upper-bound since taking
509n/a ``% 7`` in gettmarg() automatically restricts the range. */
510n/a if (buf->tm_wday < 0) {
511n/a PyErr_SetString(PyExc_ValueError, "day of week out of range");
512n/a return 0;
513n/a }
514n/a if (buf->tm_yday == -1)
515n/a buf->tm_yday = 0;
516n/a else if (buf->tm_yday < 0 || buf->tm_yday > 365) {
517n/a PyErr_SetString(PyExc_ValueError, "day of year out of range");
518n/a return 0;
519n/a }
520n/a return 1;
521n/a}
522n/a
523n/a#ifdef MS_WINDOWS
524n/a /* wcsftime() doesn't format correctly time zones, see issue #10653 */
525n/a# undef HAVE_WCSFTIME
526n/a#endif
527n/a#define STRFTIME_FORMAT_CODES \
528n/a"Commonly used format codes:\n\
529n/a\n\
530n/a%Y Year with century as a decimal number.\n\
531n/a%m Month as a decimal number [01,12].\n\
532n/a%d Day of the month as a decimal number [01,31].\n\
533n/a%H Hour (24-hour clock) as a decimal number [00,23].\n\
534n/a%M Minute as a decimal number [00,59].\n\
535n/a%S Second as a decimal number [00,61].\n\
536n/a%z Time zone offset from UTC.\n\
537n/a%a Locale's abbreviated weekday name.\n\
538n/a%A Locale's full weekday name.\n\
539n/a%b Locale's abbreviated month name.\n\
540n/a%B Locale's full month name.\n\
541n/a%c Locale's appropriate date and time representation.\n\
542n/a%I Hour (12-hour clock) as a decimal number [01,12].\n\
543n/a%p Locale's equivalent of either AM or PM.\n\
544n/a\n\
545n/aOther codes may be available on your platform. See documentation for\n\
546n/athe C library strftime function.\n"
547n/a
548n/a#ifdef HAVE_STRFTIME
549n/a#ifdef HAVE_WCSFTIME
550n/a#define time_char wchar_t
551n/a#define format_time wcsftime
552n/a#define time_strlen wcslen
553n/a#else
554n/a#define time_char char
555n/a#define format_time strftime
556n/a#define time_strlen strlen
557n/a#endif
558n/a
559n/astatic PyObject *
560n/atime_strftime(PyObject *self, PyObject *args)
561n/a{
562n/a PyObject *tup = NULL;
563n/a struct tm buf;
564n/a const time_char *fmt;
565n/a#ifdef HAVE_WCSFTIME
566n/a wchar_t *format;
567n/a#else
568n/a PyObject *format;
569n/a#endif
570n/a PyObject *format_arg;
571n/a size_t fmtlen, buflen;
572n/a time_char *outbuf = NULL;
573n/a size_t i;
574n/a PyObject *ret = NULL;
575n/a
576n/a memset((void *) &buf, '\0', sizeof(buf));
577n/a
578n/a /* Will always expect a unicode string to be passed as format.
579n/a Given that there's no str type anymore in py3k this seems safe.
580n/a */
581n/a if (!PyArg_ParseTuple(args, "U|O:strftime", &format_arg, &tup))
582n/a return NULL;
583n/a
584n/a if (tup == NULL) {
585n/a time_t tt = time(NULL);
586n/a if (_PyTime_localtime(tt, &buf) != 0)
587n/a return NULL;
588n/a }
589n/a else if (!gettmarg(tup, &buf) || !checktm(&buf))
590n/a return NULL;
591n/a
592n/a#if defined(_MSC_VER) || defined(sun) || defined(_AIX)
593n/a if (buf.tm_year + 1900 < 1 || 9999 < buf.tm_year + 1900) {
594n/a PyErr_SetString(PyExc_ValueError,
595n/a "strftime() requires year in [1; 9999]");
596n/a return NULL;
597n/a }
598n/a#endif
599n/a
600n/a /* Normalize tm_isdst just in case someone foolishly implements %Z
601n/a based on the assumption that tm_isdst falls within the range of
602n/a [-1, 1] */
603n/a if (buf.tm_isdst < -1)
604n/a buf.tm_isdst = -1;
605n/a else if (buf.tm_isdst > 1)
606n/a buf.tm_isdst = 1;
607n/a
608n/a#ifdef HAVE_WCSFTIME
609n/a format = PyUnicode_AsWideCharString(format_arg, NULL);
610n/a if (format == NULL)
611n/a return NULL;
612n/a fmt = format;
613n/a#else
614n/a /* Convert the unicode string to an ascii one */
615n/a format = PyUnicode_EncodeLocale(format_arg, "surrogateescape");
616n/a if (format == NULL)
617n/a return NULL;
618n/a fmt = PyBytes_AS_STRING(format);
619n/a#endif
620n/a
621n/a#if defined(MS_WINDOWS) && !defined(HAVE_WCSFTIME)
622n/a /* check that the format string contains only valid directives */
623n/a for (outbuf = strchr(fmt, '%');
624n/a outbuf != NULL;
625n/a outbuf = strchr(outbuf+2, '%'))
626n/a {
627n/a if (outbuf[1] == '#')
628n/a ++outbuf; /* not documented by python, */
629n/a if (outbuf[1] == '\0')
630n/a break;
631n/a if ((outbuf[1] == 'y') && buf.tm_year < 0) {
632n/a PyErr_SetString(PyExc_ValueError,
633n/a "format %y requires year >= 1900 on Windows");
634n/a Py_DECREF(format);
635n/a return NULL;
636n/a }
637n/a }
638n/a#elif (defined(_AIX) || defined(sun)) && defined(HAVE_WCSFTIME)
639n/a for (outbuf = wcschr(fmt, '%');
640n/a outbuf != NULL;
641n/a outbuf = wcschr(outbuf+2, '%'))
642n/a {
643n/a if (outbuf[1] == L'\0')
644n/a break;
645n/a /* Issue #19634: On AIX, wcsftime("y", (1899, 1, 1, 0, 0, 0, 0, 0, 0))
646n/a returns "0/" instead of "99" */
647n/a if (outbuf[1] == L'y' && buf.tm_year < 0) {
648n/a PyErr_SetString(PyExc_ValueError,
649n/a "format %y requires year >= 1900 on AIX");
650n/a return NULL;
651n/a }
652n/a }
653n/a#endif
654n/a
655n/a fmtlen = time_strlen(fmt);
656n/a
657n/a /* I hate these functions that presume you know how big the output
658n/a * will be ahead of time...
659n/a */
660n/a for (i = 1024; ; i += i) {
661n/a outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char));
662n/a if (outbuf == NULL) {
663n/a PyErr_NoMemory();
664n/a break;
665n/a }
666n/a#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
667n/a errno = 0;
668n/a#endif
669n/a _Py_BEGIN_SUPPRESS_IPH
670n/a buflen = format_time(outbuf, i, fmt, &buf);
671n/a _Py_END_SUPPRESS_IPH
672n/a#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
673n/a /* VisualStudio .NET 2005 does this properly */
674n/a if (buflen == 0 && errno == EINVAL) {
675n/a PyErr_SetString(PyExc_ValueError, "Invalid format string");
676n/a PyMem_Free(outbuf);
677n/a break;
678n/a }
679n/a#endif
680n/a if (buflen > 0 || i >= 256 * fmtlen) {
681n/a /* If the buffer is 256 times as long as the format,
682n/a it's probably not failing for lack of room!
683n/a More likely, the format yields an empty result,
684n/a e.g. an empty format, or %Z when the timezone
685n/a is unknown. */
686n/a#ifdef HAVE_WCSFTIME
687n/a ret = PyUnicode_FromWideChar(outbuf, buflen);
688n/a#else
689n/a ret = PyUnicode_DecodeLocaleAndSize(outbuf, buflen,
690n/a "surrogateescape");
691n/a#endif
692n/a PyMem_Free(outbuf);
693n/a break;
694n/a }
695n/a PyMem_Free(outbuf);
696n/a }
697n/a#ifdef HAVE_WCSFTIME
698n/a PyMem_Free(format);
699n/a#else
700n/a Py_DECREF(format);
701n/a#endif
702n/a return ret;
703n/a}
704n/a
705n/a#undef time_char
706n/a#undef format_time
707n/aPyDoc_STRVAR(strftime_doc,
708n/a"strftime(format[, tuple]) -> string\n\
709n/a\n\
710n/aConvert a time tuple to a string according to a format specification.\n\
711n/aSee the library reference manual for formatting codes. When the time tuple\n\
712n/ais not present, current time as returned by localtime() is used.\n\
713n/a\n" STRFTIME_FORMAT_CODES);
714n/a#endif /* HAVE_STRFTIME */
715n/a
716n/astatic PyObject *
717n/atime_strptime(PyObject *self, PyObject *args)
718n/a{
719n/a PyObject *module, *func, *result;
720n/a _Py_IDENTIFIER(_strptime_time);
721n/a
722n/a module = PyImport_ImportModuleNoBlock("_strptime");
723n/a if (!module)
724n/a return NULL;
725n/a
726n/a func = _PyObject_GetAttrId(module, &PyId__strptime_time);
727n/a Py_DECREF(module);
728n/a if (!func) {
729n/a return NULL;
730n/a }
731n/a
732n/a result = PyObject_Call(func, args, NULL);
733n/a Py_DECREF(func);
734n/a return result;
735n/a}
736n/a
737n/a
738n/aPyDoc_STRVAR(strptime_doc,
739n/a"strptime(string, format) -> struct_time\n\
740n/a\n\
741n/aParse a string to a time tuple according to a format specification.\n\
742n/aSee the library reference manual for formatting codes (same as\n\
743n/astrftime()).\n\
744n/a\n" STRFTIME_FORMAT_CODES);
745n/a
746n/astatic PyObject *
747n/a_asctime(struct tm *timeptr)
748n/a{
749n/a /* Inspired by Open Group reference implementation available at
750n/a * http://pubs.opengroup.org/onlinepubs/009695399/functions/asctime.html */
751n/a static const char wday_name[7][4] = {
752n/a "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
753n/a };
754n/a static const char mon_name[12][4] = {
755n/a "Jan", "Feb", "Mar", "Apr", "May", "Jun",
756n/a "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
757n/a };
758n/a return PyUnicode_FromFormat(
759n/a "%s %s%3d %.2d:%.2d:%.2d %d",
760n/a wday_name[timeptr->tm_wday],
761n/a mon_name[timeptr->tm_mon],
762n/a timeptr->tm_mday, timeptr->tm_hour,
763n/a timeptr->tm_min, timeptr->tm_sec,
764n/a 1900 + timeptr->tm_year);
765n/a}
766n/a
767n/astatic PyObject *
768n/atime_asctime(PyObject *self, PyObject *args)
769n/a{
770n/a PyObject *tup = NULL;
771n/a struct tm buf;
772n/a
773n/a if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
774n/a return NULL;
775n/a if (tup == NULL) {
776n/a time_t tt = time(NULL);
777n/a if (_PyTime_localtime(tt, &buf) != 0)
778n/a return NULL;
779n/a
780n/a } else if (!gettmarg(tup, &buf) || !checktm(&buf))
781n/a return NULL;
782n/a return _asctime(&buf);
783n/a}
784n/a
785n/aPyDoc_STRVAR(asctime_doc,
786n/a"asctime([tuple]) -> string\n\
787n/a\n\
788n/aConvert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
789n/aWhen the time tuple is not present, current time as returned by localtime()\n\
790n/ais used.");
791n/a
792n/astatic PyObject *
793n/atime_ctime(PyObject *self, PyObject *args)
794n/a{
795n/a time_t tt;
796n/a struct tm buf;
797n/a if (!parse_time_t_args(args, "|O:ctime", &tt))
798n/a return NULL;
799n/a if (_PyTime_localtime(tt, &buf) != 0)
800n/a return NULL;
801n/a return _asctime(&buf);
802n/a}
803n/a
804n/aPyDoc_STRVAR(ctime_doc,
805n/a"ctime(seconds) -> string\n\
806n/a\n\
807n/aConvert a time in seconds since the Epoch to a string in local time.\n\
808n/aThis is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
809n/anot present, current time as returned by localtime() is used.");
810n/a
811n/a#ifdef HAVE_MKTIME
812n/astatic PyObject *
813n/atime_mktime(PyObject *self, PyObject *tup)
814n/a{
815n/a struct tm buf;
816n/a time_t tt;
817n/a if (!gettmarg(tup, &buf))
818n/a return NULL;
819n/a#ifdef _AIX
820n/a /* year < 1902 or year > 2037 */
821n/a if (buf.tm_year < 2 || buf.tm_year > 137) {
822n/a /* Issue #19748: On AIX, mktime() doesn't report overflow error for
823n/a * timestamp < -2^31 or timestamp > 2**31-1. */
824n/a PyErr_SetString(PyExc_OverflowError,
825n/a "mktime argument out of range");
826n/a return NULL;
827n/a }
828n/a#else
829n/a buf.tm_wday = -1; /* sentinel; original value ignored */
830n/a#endif
831n/a tt = mktime(&buf);
832n/a /* Return value of -1 does not necessarily mean an error, but tm_wday
833n/a * cannot remain set to -1 if mktime succeeded. */
834n/a if (tt == (time_t)(-1)
835n/a#ifndef _AIX
836n/a /* Return value of -1 does not necessarily mean an error, but
837n/a * tm_wday cannot remain set to -1 if mktime succeeded. */
838n/a && buf.tm_wday == -1
839n/a#else
840n/a /* on AIX, tm_wday is always sets, even on error */
841n/a#endif
842n/a )
843n/a {
844n/a PyErr_SetString(PyExc_OverflowError,
845n/a "mktime argument out of range");
846n/a return NULL;
847n/a }
848n/a return PyFloat_FromDouble((double)tt);
849n/a}
850n/a
851n/aPyDoc_STRVAR(mktime_doc,
852n/a"mktime(tuple) -> floating point number\n\
853n/a\n\
854n/aConvert a time tuple in local time to seconds since the Epoch.\n\
855n/aNote that mktime(gmtime(0)) will not generally return zero for most\n\
856n/atime zones; instead the returned value will either be equal to that\n\
857n/aof the timezone or altzone attributes on the time module.");
858n/a#endif /* HAVE_MKTIME */
859n/a
860n/a#ifdef HAVE_WORKING_TZSET
861n/astatic void PyInit_timezone(PyObject *module);
862n/a
863n/astatic PyObject *
864n/atime_tzset(PyObject *self, PyObject *unused)
865n/a{
866n/a PyObject* m;
867n/a
868n/a m = PyImport_ImportModuleNoBlock("time");
869n/a if (m == NULL) {
870n/a return NULL;
871n/a }
872n/a
873n/a tzset();
874n/a
875n/a /* Reset timezone, altzone, daylight and tzname */
876n/a PyInit_timezone(m);
877n/a Py_DECREF(m);
878n/a if (PyErr_Occurred())
879n/a return NULL;
880n/a
881n/a Py_RETURN_NONE;
882n/a}
883n/a
884n/aPyDoc_STRVAR(tzset_doc,
885n/a"tzset()\n\
886n/a\n\
887n/aInitialize, or reinitialize, the local timezone to the value stored in\n\
888n/aos.environ['TZ']. The TZ environment variable should be specified in\n\
889n/astandard Unix timezone format as documented in the tzset man page\n\
890n/a(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
891n/afall back to UTC. If the TZ environment variable is not set, the local\n\
892n/atimezone is set to the systems best guess of wallclock time.\n\
893n/aChanging the TZ environment variable without calling tzset *may* change\n\
894n/athe local timezone used by methods such as localtime, but this behaviour\n\
895n/ashould not be relied on.");
896n/a#endif /* HAVE_WORKING_TZSET */
897n/a
898n/astatic PyObject *
899n/apymonotonic(_Py_clock_info_t *info)
900n/a{
901n/a _PyTime_t t;
902n/a double d;
903n/a if (_PyTime_GetMonotonicClockWithInfo(&t, info) < 0) {
904n/a assert(info != NULL);
905n/a return NULL;
906n/a }
907n/a d = _PyTime_AsSecondsDouble(t);
908n/a return PyFloat_FromDouble(d);
909n/a}
910n/a
911n/astatic PyObject *
912n/atime_monotonic(PyObject *self, PyObject *unused)
913n/a{
914n/a return pymonotonic(NULL);
915n/a}
916n/a
917n/aPyDoc_STRVAR(monotonic_doc,
918n/a"monotonic() -> float\n\
919n/a\n\
920n/aMonotonic clock, cannot go backward.");
921n/a
922n/astatic PyObject*
923n/aperf_counter(_Py_clock_info_t *info)
924n/a{
925n/a#ifdef WIN32_PERF_COUNTER
926n/a return win_perf_counter(info);
927n/a#else
928n/a return pymonotonic(info);
929n/a#endif
930n/a}
931n/a
932n/astatic PyObject *
933n/atime_perf_counter(PyObject *self, PyObject *unused)
934n/a{
935n/a return perf_counter(NULL);
936n/a}
937n/a
938n/aPyDoc_STRVAR(perf_counter_doc,
939n/a"perf_counter() -> float\n\
940n/a\n\
941n/aPerformance counter for benchmarking.");
942n/a
943n/astatic PyObject*
944n/apy_process_time(_Py_clock_info_t *info)
945n/a{
946n/a#if defined(MS_WINDOWS)
947n/a HANDLE process;
948n/a FILETIME creation_time, exit_time, kernel_time, user_time;
949n/a ULARGE_INTEGER large;
950n/a double total;
951n/a BOOL ok;
952n/a
953n/a process = GetCurrentProcess();
954n/a ok = GetProcessTimes(process, &creation_time, &exit_time, &kernel_time, &user_time);
955n/a if (!ok)
956n/a return PyErr_SetFromWindowsErr(0);
957n/a
958n/a large.u.LowPart = kernel_time.dwLowDateTime;
959n/a large.u.HighPart = kernel_time.dwHighDateTime;
960n/a total = (double)large.QuadPart;
961n/a large.u.LowPart = user_time.dwLowDateTime;
962n/a large.u.HighPart = user_time.dwHighDateTime;
963n/a total += (double)large.QuadPart;
964n/a if (info) {
965n/a info->implementation = "GetProcessTimes()";
966n/a info->resolution = 1e-7;
967n/a info->monotonic = 1;
968n/a info->adjustable = 0;
969n/a }
970n/a return PyFloat_FromDouble(total * 1e-7);
971n/a#else
972n/a
973n/a#if defined(HAVE_SYS_RESOURCE_H)
974n/a struct rusage ru;
975n/a#endif
976n/a#ifdef HAVE_TIMES
977n/a struct tms t;
978n/a static long ticks_per_second = -1;
979n/a#endif
980n/a
981n/a#if defined(HAVE_CLOCK_GETTIME) \
982n/a && (defined(CLOCK_PROCESS_CPUTIME_ID) || defined(CLOCK_PROF))
983n/a struct timespec tp;
984n/a#ifdef CLOCK_PROF
985n/a const clockid_t clk_id = CLOCK_PROF;
986n/a const char *function = "clock_gettime(CLOCK_PROF)";
987n/a#else
988n/a const clockid_t clk_id = CLOCK_PROCESS_CPUTIME_ID;
989n/a const char *function = "clock_gettime(CLOCK_PROCESS_CPUTIME_ID)";
990n/a#endif
991n/a
992n/a if (clock_gettime(clk_id, &tp) == 0) {
993n/a if (info) {
994n/a struct timespec res;
995n/a info->implementation = function;
996n/a info->monotonic = 1;
997n/a info->adjustable = 0;
998n/a if (clock_getres(clk_id, &res) == 0)
999n/a info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
1000n/a else
1001n/a info->resolution = 1e-9;
1002n/a }
1003n/a return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
1004n/a }
1005n/a#endif
1006n/a
1007n/a#if defined(HAVE_SYS_RESOURCE_H)
1008n/a if (getrusage(RUSAGE_SELF, &ru) == 0) {
1009n/a double total;
1010n/a total = ru.ru_utime.tv_sec + ru.ru_utime.tv_usec * 1e-6;
1011n/a total += ru.ru_stime.tv_sec + ru.ru_stime.tv_usec * 1e-6;
1012n/a if (info) {
1013n/a info->implementation = "getrusage(RUSAGE_SELF)";
1014n/a info->monotonic = 1;
1015n/a info->adjustable = 0;
1016n/a info->resolution = 1e-6;
1017n/a }
1018n/a return PyFloat_FromDouble(total);
1019n/a }
1020n/a#endif
1021n/a
1022n/a#ifdef HAVE_TIMES
1023n/a if (times(&t) != (clock_t)-1) {
1024n/a double total;
1025n/a
1026n/a if (ticks_per_second == -1) {
1027n/a#if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
1028n/a ticks_per_second = sysconf(_SC_CLK_TCK);
1029n/a if (ticks_per_second < 1)
1030n/a ticks_per_second = -1;
1031n/a#elif defined(HZ)
1032n/a ticks_per_second = HZ;
1033n/a#else
1034n/a ticks_per_second = 60; /* magic fallback value; may be bogus */
1035n/a#endif
1036n/a }
1037n/a
1038n/a if (ticks_per_second != -1) {
1039n/a total = (double)t.tms_utime / ticks_per_second;
1040n/a total += (double)t.tms_stime / ticks_per_second;
1041n/a if (info) {
1042n/a info->implementation = "times()";
1043n/a info->monotonic = 1;
1044n/a info->adjustable = 0;
1045n/a info->resolution = 1.0 / ticks_per_second;
1046n/a }
1047n/a return PyFloat_FromDouble(total);
1048n/a }
1049n/a }
1050n/a#endif
1051n/a
1052n/a /* Currently, Python 3 requires clock() to build: see issue #22624 */
1053n/a return floatclock(info);
1054n/a#endif
1055n/a}
1056n/a
1057n/astatic PyObject *
1058n/atime_process_time(PyObject *self, PyObject *unused)
1059n/a{
1060n/a return py_process_time(NULL);
1061n/a}
1062n/a
1063n/aPyDoc_STRVAR(process_time_doc,
1064n/a"process_time() -> float\n\
1065n/a\n\
1066n/aProcess time for profiling: sum of the kernel and user-space CPU time.");
1067n/a
1068n/a
1069n/astatic PyObject *
1070n/atime_get_clock_info(PyObject *self, PyObject *args)
1071n/a{
1072n/a char *name;
1073n/a _Py_clock_info_t info;
1074n/a PyObject *obj = NULL, *dict, *ns;
1075n/a
1076n/a if (!PyArg_ParseTuple(args, "s:get_clock_info", &name))
1077n/a return NULL;
1078n/a
1079n/a#ifdef Py_DEBUG
1080n/a info.implementation = NULL;
1081n/a info.monotonic = -1;
1082n/a info.adjustable = -1;
1083n/a info.resolution = -1.0;
1084n/a#else
1085n/a info.implementation = "";
1086n/a info.monotonic = 0;
1087n/a info.adjustable = 0;
1088n/a info.resolution = 1.0;
1089n/a#endif
1090n/a
1091n/a if (strcmp(name, "time") == 0)
1092n/a obj = floattime(&info);
1093n/a#ifdef PYCLOCK
1094n/a else if (strcmp(name, "clock") == 0)
1095n/a obj = pyclock(&info);
1096n/a#endif
1097n/a else if (strcmp(name, "monotonic") == 0)
1098n/a obj = pymonotonic(&info);
1099n/a else if (strcmp(name, "perf_counter") == 0)
1100n/a obj = perf_counter(&info);
1101n/a else if (strcmp(name, "process_time") == 0)
1102n/a obj = py_process_time(&info);
1103n/a else {
1104n/a PyErr_SetString(PyExc_ValueError, "unknown clock");
1105n/a return NULL;
1106n/a }
1107n/a if (obj == NULL)
1108n/a return NULL;
1109n/a Py_DECREF(obj);
1110n/a
1111n/a dict = PyDict_New();
1112n/a if (dict == NULL)
1113n/a return NULL;
1114n/a
1115n/a assert(info.implementation != NULL);
1116n/a obj = PyUnicode_FromString(info.implementation);
1117n/a if (obj == NULL)
1118n/a goto error;
1119n/a if (PyDict_SetItemString(dict, "implementation", obj) == -1)
1120n/a goto error;
1121n/a Py_CLEAR(obj);
1122n/a
1123n/a assert(info.monotonic != -1);
1124n/a obj = PyBool_FromLong(info.monotonic);
1125n/a if (obj == NULL)
1126n/a goto error;
1127n/a if (PyDict_SetItemString(dict, "monotonic", obj) == -1)
1128n/a goto error;
1129n/a Py_CLEAR(obj);
1130n/a
1131n/a assert(info.adjustable != -1);
1132n/a obj = PyBool_FromLong(info.adjustable);
1133n/a if (obj == NULL)
1134n/a goto error;
1135n/a if (PyDict_SetItemString(dict, "adjustable", obj) == -1)
1136n/a goto error;
1137n/a Py_CLEAR(obj);
1138n/a
1139n/a assert(info.resolution > 0.0);
1140n/a assert(info.resolution <= 1.0);
1141n/a obj = PyFloat_FromDouble(info.resolution);
1142n/a if (obj == NULL)
1143n/a goto error;
1144n/a if (PyDict_SetItemString(dict, "resolution", obj) == -1)
1145n/a goto error;
1146n/a Py_CLEAR(obj);
1147n/a
1148n/a ns = _PyNamespace_New(dict);
1149n/a Py_DECREF(dict);
1150n/a return ns;
1151n/a
1152n/aerror:
1153n/a Py_DECREF(dict);
1154n/a Py_XDECREF(obj);
1155n/a return NULL;
1156n/a}
1157n/a
1158n/aPyDoc_STRVAR(get_clock_info_doc,
1159n/a"get_clock_info(name: str) -> dict\n\
1160n/a\n\
1161n/aGet information of the specified clock.");
1162n/a
1163n/astatic void
1164n/aget_zone(char *zone, int n, struct tm *p)
1165n/a{
1166n/a#ifdef HAVE_STRUCT_TM_TM_ZONE
1167n/a strncpy(zone, p->tm_zone ? p->tm_zone : " ", n);
1168n/a#else
1169n/a tzset();
1170n/a strftime(zone, n, "%Z", p);
1171n/a#endif
1172n/a}
1173n/a
1174n/astatic int
1175n/aget_gmtoff(time_t t, struct tm *p)
1176n/a{
1177n/a#ifdef HAVE_STRUCT_TM_TM_ZONE
1178n/a return p->tm_gmtoff;
1179n/a#else
1180n/a return timegm(p) - t;
1181n/a#endif
1182n/a}
1183n/a
1184n/astatic void
1185n/aPyInit_timezone(PyObject *m) {
1186n/a /* This code moved from PyInit_time wholesale to allow calling it from
1187n/a time_tzset. In the future, some parts of it can be moved back
1188n/a (for platforms that don't HAVE_WORKING_TZSET, when we know what they
1189n/a are), and the extraneous calls to tzset(3) should be removed.
1190n/a I haven't done this yet, as I don't want to change this code as
1191n/a little as possible when introducing the time.tzset and time.tzsetwall
1192n/a methods. This should simply be a method of doing the following once,
1193n/a at the top of this function and removing the call to tzset() from
1194n/a time_tzset():
1195n/a
1196n/a #ifdef HAVE_TZSET
1197n/a tzset()
1198n/a #endif
1199n/a
1200n/a And I'm lazy and hate C so nyer.
1201n/a */
1202n/a#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
1203n/a PyObject *otz0, *otz1;
1204n/a tzset();
1205n/a PyModule_AddIntConstant(m, "timezone", timezone);
1206n/a#ifdef HAVE_ALTZONE
1207n/a PyModule_AddIntConstant(m, "altzone", altzone);
1208n/a#else
1209n/a PyModule_AddIntConstant(m, "altzone", timezone-3600);
1210n/a#endif
1211n/a PyModule_AddIntConstant(m, "daylight", daylight);
1212n/a otz0 = PyUnicode_DecodeLocale(tzname[0], "surrogateescape");
1213n/a otz1 = PyUnicode_DecodeLocale(tzname[1], "surrogateescape");
1214n/a PyModule_AddObject(m, "tzname", Py_BuildValue("(NN)", otz0, otz1));
1215n/a#else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
1216n/a {
1217n/a#define YEAR ((time_t)((365 * 24 + 6) * 3600))
1218n/a time_t t;
1219n/a struct tm p;
1220n/a long janzone, julyzone;
1221n/a char janname[10], julyname[10];
1222n/a t = (time((time_t *)0) / YEAR) * YEAR;
1223n/a _PyTime_localtime(t, &p);
1224n/a get_zone(janname, 9, &p);
1225n/a janzone = -get_gmtoff(t, &p);
1226n/a janname[9] = '\0';
1227n/a t += YEAR/2;
1228n/a _PyTime_localtime(t, &p);
1229n/a get_zone(julyname, 9, &p);
1230n/a julyzone = -get_gmtoff(t, &p);
1231n/a julyname[9] = '\0';
1232n/a
1233n/a if( janzone < julyzone ) {
1234n/a /* DST is reversed in the southern hemisphere */
1235n/a PyModule_AddIntConstant(m, "timezone", julyzone);
1236n/a PyModule_AddIntConstant(m, "altzone", janzone);
1237n/a PyModule_AddIntConstant(m, "daylight",
1238n/a janzone != julyzone);
1239n/a PyModule_AddObject(m, "tzname",
1240n/a Py_BuildValue("(zz)",
1241n/a julyname, janname));
1242n/a } else {
1243n/a PyModule_AddIntConstant(m, "timezone", janzone);
1244n/a PyModule_AddIntConstant(m, "altzone", julyzone);
1245n/a PyModule_AddIntConstant(m, "daylight",
1246n/a janzone != julyzone);
1247n/a PyModule_AddObject(m, "tzname",
1248n/a Py_BuildValue("(zz)",
1249n/a janname, julyname));
1250n/a }
1251n/a }
1252n/a#ifdef __CYGWIN__
1253n/a tzset();
1254n/a PyModule_AddIntConstant(m, "timezone", _timezone);
1255n/a PyModule_AddIntConstant(m, "altzone", _timezone-3600);
1256n/a PyModule_AddIntConstant(m, "daylight", _daylight);
1257n/a PyModule_AddObject(m, "tzname",
1258n/a Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
1259n/a#endif /* __CYGWIN__ */
1260n/a#endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
1261n/a}
1262n/a
1263n/a
1264n/astatic PyMethodDef time_methods[] = {
1265n/a {"time", time_time, METH_NOARGS, time_doc},
1266n/a#ifdef PYCLOCK
1267n/a {"clock", time_clock, METH_NOARGS, clock_doc},
1268n/a#endif
1269n/a#ifdef HAVE_CLOCK_GETTIME
1270n/a {"clock_gettime", time_clock_gettime, METH_VARARGS, clock_gettime_doc},
1271n/a#endif
1272n/a#ifdef HAVE_CLOCK_SETTIME
1273n/a {"clock_settime", time_clock_settime, METH_VARARGS, clock_settime_doc},
1274n/a#endif
1275n/a#ifdef HAVE_CLOCK_GETRES
1276n/a {"clock_getres", time_clock_getres, METH_VARARGS, clock_getres_doc},
1277n/a#endif
1278n/a {"sleep", time_sleep, METH_O, sleep_doc},
1279n/a {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
1280n/a {"localtime", time_localtime, METH_VARARGS, localtime_doc},
1281n/a {"asctime", time_asctime, METH_VARARGS, asctime_doc},
1282n/a {"ctime", time_ctime, METH_VARARGS, ctime_doc},
1283n/a#ifdef HAVE_MKTIME
1284n/a {"mktime", time_mktime, METH_O, mktime_doc},
1285n/a#endif
1286n/a#ifdef HAVE_STRFTIME
1287n/a {"strftime", time_strftime, METH_VARARGS, strftime_doc},
1288n/a#endif
1289n/a {"strptime", time_strptime, METH_VARARGS, strptime_doc},
1290n/a#ifdef HAVE_WORKING_TZSET
1291n/a {"tzset", time_tzset, METH_NOARGS, tzset_doc},
1292n/a#endif
1293n/a {"monotonic", time_monotonic, METH_NOARGS, monotonic_doc},
1294n/a {"process_time", time_process_time, METH_NOARGS, process_time_doc},
1295n/a {"perf_counter", time_perf_counter, METH_NOARGS, perf_counter_doc},
1296n/a {"get_clock_info", time_get_clock_info, METH_VARARGS, get_clock_info_doc},
1297n/a {NULL, NULL} /* sentinel */
1298n/a};
1299n/a
1300n/a
1301n/aPyDoc_STRVAR(module_doc,
1302n/a"This module provides various functions to manipulate time values.\n\
1303n/a\n\
1304n/aThere are two standard representations of time. One is the number\n\
1305n/aof seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
1306n/aor a floating point number (to represent fractions of seconds).\n\
1307n/aThe Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
1308n/aThe actual value can be retrieved by calling gmtime(0).\n\
1309n/a\n\
1310n/aThe other representation is a tuple of 9 integers giving local time.\n\
1311n/aThe tuple items are:\n\
1312n/a year (including century, e.g. 1998)\n\
1313n/a month (1-12)\n\
1314n/a day (1-31)\n\
1315n/a hours (0-23)\n\
1316n/a minutes (0-59)\n\
1317n/a seconds (0-59)\n\
1318n/a weekday (0-6, Monday is 0)\n\
1319n/a Julian day (day in the year, 1-366)\n\
1320n/a DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
1321n/aIf the DST flag is 0, the time is given in the regular time zone;\n\
1322n/aif it is 1, the time is given in the DST time zone;\n\
1323n/aif it is -1, mktime() should guess based on the date and time.\n\
1324n/a\n\
1325n/aVariables:\n\
1326n/a\n\
1327n/atimezone -- difference in seconds between UTC and local standard time\n\
1328n/aaltzone -- difference in seconds between UTC and local DST time\n\
1329n/adaylight -- whether local time should reflect DST\n\
1330n/atzname -- tuple of (standard time zone name, DST time zone name)\n\
1331n/a\n\
1332n/aFunctions:\n\
1333n/a\n\
1334n/atime() -- return current time in seconds since the Epoch as a float\n\
1335n/aclock() -- return CPU time since process start as a float\n\
1336n/asleep() -- delay for a number of seconds given as a float\n\
1337n/agmtime() -- convert seconds since Epoch to UTC tuple\n\
1338n/alocaltime() -- convert seconds since Epoch to local time tuple\n\
1339n/aasctime() -- convert time tuple to string\n\
1340n/actime() -- convert time in seconds to string\n\
1341n/amktime() -- convert local time tuple to seconds since Epoch\n\
1342n/astrftime() -- convert time tuple to string according to format specification\n\
1343n/astrptime() -- parse string to time tuple according to format specification\n\
1344n/atzset() -- change the local timezone");
1345n/a
1346n/a
1347n/a
1348n/astatic struct PyModuleDef timemodule = {
1349n/a PyModuleDef_HEAD_INIT,
1350n/a "time",
1351n/a module_doc,
1352n/a -1,
1353n/a time_methods,
1354n/a NULL,
1355n/a NULL,
1356n/a NULL,
1357n/a NULL
1358n/a};
1359n/a
1360n/aPyMODINIT_FUNC
1361n/aPyInit_time(void)
1362n/a{
1363n/a PyObject *m;
1364n/a m = PyModule_Create(&timemodule);
1365n/a if (m == NULL)
1366n/a return NULL;
1367n/a
1368n/a /* Set, or reset, module variables like time.timezone */
1369n/a PyInit_timezone(m);
1370n/a
1371n/a#ifdef CLOCK_REALTIME
1372n/a PyModule_AddIntMacro(m, CLOCK_REALTIME);
1373n/a#endif
1374n/a#ifdef CLOCK_MONOTONIC
1375n/a PyModule_AddIntMacro(m, CLOCK_MONOTONIC);
1376n/a#endif
1377n/a#ifdef CLOCK_MONOTONIC_RAW
1378n/a PyModule_AddIntMacro(m, CLOCK_MONOTONIC_RAW);
1379n/a#endif
1380n/a#ifdef CLOCK_HIGHRES
1381n/a PyModule_AddIntMacro(m, CLOCK_HIGHRES);
1382n/a#endif
1383n/a#ifdef CLOCK_PROCESS_CPUTIME_ID
1384n/a PyModule_AddIntMacro(m, CLOCK_PROCESS_CPUTIME_ID);
1385n/a#endif
1386n/a#ifdef CLOCK_THREAD_CPUTIME_ID
1387n/a PyModule_AddIntMacro(m, CLOCK_THREAD_CPUTIME_ID);
1388n/a#endif
1389n/a
1390n/a if (!initialized) {
1391n/a if (PyStructSequence_InitType2(&StructTimeType,
1392n/a &struct_time_type_desc) < 0)
1393n/a return NULL;
1394n/a }
1395n/a Py_INCREF(&StructTimeType);
1396n/a PyModule_AddIntConstant(m, "_STRUCT_TM_ITEMS", 11);
1397n/a PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
1398n/a initialized = 1;
1399n/a return m;
1400n/a}
1401n/a
1402n/astatic PyObject*
1403n/afloattime(_Py_clock_info_t *info)
1404n/a{
1405n/a _PyTime_t t;
1406n/a double d;
1407n/a if (_PyTime_GetSystemClockWithInfo(&t, info) < 0) {
1408n/a assert(info != NULL);
1409n/a return NULL;
1410n/a }
1411n/a d = _PyTime_AsSecondsDouble(t);
1412n/a return PyFloat_FromDouble(d);
1413n/a}
1414n/a
1415n/a
1416n/a/* Implement pysleep() for various platforms.
1417n/a When interrupted (or when another error occurs), return -1 and
1418n/a set an exception; else return 0. */
1419n/a
1420n/astatic int
1421n/apysleep(_PyTime_t secs)
1422n/a{
1423n/a _PyTime_t deadline, monotonic;
1424n/a#ifndef MS_WINDOWS
1425n/a struct timeval timeout;
1426n/a int err = 0;
1427n/a#else
1428n/a _PyTime_t millisecs;
1429n/a unsigned long ul_millis;
1430n/a DWORD rc;
1431n/a HANDLE hInterruptEvent;
1432n/a#endif
1433n/a
1434n/a deadline = _PyTime_GetMonotonicClock() + secs;
1435n/a
1436n/a do {
1437n/a#ifndef MS_WINDOWS
1438n/a if (_PyTime_AsTimeval(secs, &timeout, _PyTime_ROUND_CEILING) < 0)
1439n/a return -1;
1440n/a
1441n/a Py_BEGIN_ALLOW_THREADS
1442n/a err = select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &timeout);
1443n/a Py_END_ALLOW_THREADS
1444n/a
1445n/a if (err == 0)
1446n/a break;
1447n/a
1448n/a if (errno != EINTR) {
1449n/a PyErr_SetFromErrno(PyExc_OSError);
1450n/a return -1;
1451n/a }
1452n/a#else
1453n/a millisecs = _PyTime_AsMilliseconds(secs, _PyTime_ROUND_CEILING);
1454n/a if (millisecs > (double)ULONG_MAX) {
1455n/a PyErr_SetString(PyExc_OverflowError,
1456n/a "sleep length is too large");
1457n/a return -1;
1458n/a }
1459n/a
1460n/a /* Allow sleep(0) to maintain win32 semantics, and as decreed
1461n/a * by Guido, only the main thread can be interrupted.
1462n/a */
1463n/a ul_millis = (unsigned long)millisecs;
1464n/a if (ul_millis == 0 || !_PyOS_IsMainThread()) {
1465n/a Py_BEGIN_ALLOW_THREADS
1466n/a Sleep(ul_millis);
1467n/a Py_END_ALLOW_THREADS
1468n/a break;
1469n/a }
1470n/a
1471n/a hInterruptEvent = _PyOS_SigintEvent();
1472n/a ResetEvent(hInterruptEvent);
1473n/a
1474n/a Py_BEGIN_ALLOW_THREADS
1475n/a rc = WaitForSingleObjectEx(hInterruptEvent, ul_millis, FALSE);
1476n/a Py_END_ALLOW_THREADS
1477n/a
1478n/a if (rc != WAIT_OBJECT_0)
1479n/a break;
1480n/a#endif
1481n/a
1482n/a /* sleep was interrupted by SIGINT */
1483n/a if (PyErr_CheckSignals())
1484n/a return -1;
1485n/a
1486n/a monotonic = _PyTime_GetMonotonicClock();
1487n/a secs = deadline - monotonic;
1488n/a if (secs < 0)
1489n/a break;
1490n/a /* retry with the recomputed delay */
1491n/a } while (1);
1492n/a
1493n/a return 0;
1494n/a}