Skip to content

Commit a9459bc

Browse files
committed
unix: Add basic time module (with time() and clock() functions).
Both return int so far (single-precision float doesn't have enough bits to represent int32 precisely).
1 parent 513e656 commit a9459bc

4 files changed

Lines changed: 36 additions & 0 deletions

File tree

unix/Makefile

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,10 @@ include ../py/py.mk
1414
CFLAGS = -I. -I$(PY_SRC) -Wall -Werror -ansi -std=gnu99 -DUNIX $(CFLAGS_MOD)
1515
LDFLAGS = $(LDFLAGS_MOD) -lm
1616

17+
ifeq ($(MICROPY_MOD_TIME),1)
18+
CFLAGS_MOD += -DMICROPY_MOD_TIME=1
19+
SRC_MOD += time.c
20+
endif
1721
ifeq ($(MICROPY_MOD_FFI),1)
1822
CFLAGS_MOD += `pkg-config --cflags libffi` -DMICROPY_MOD_FFI=1
1923
LDFLAGS_MOD += -ldl -lffi

unix/main.c

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
extern const mp_obj_fun_native_t mp_builtin_open_obj;
2525
void file_init();
2626
void rawsocket_init();
27+
void time_init();
2728
void ffi_init();
2829

2930
static void execute_from_lexer(mp_lexer_t *lex, mp_parse_input_kind_t input_kind, bool is_repl) {
@@ -242,6 +243,9 @@ int main(int argc, char **argv) {
242243

243244
file_init();
244245
rawsocket_init();
246+
#if MICROPY_MOD_TIME
247+
time_init();
248+
#endif
245249
#if MICROPY_MOD_FFI
246250
ffi_init();
247251
#endif

unix/mpconfigport.mk

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
11
# Enable/disable modules to be included in interpreter
22

3+
# Subset of CPython time module
4+
MICROPY_MOD_TIME = 1
5+
36
# ffi module requires libffi (libffi-dev Debian package)
47
MICROPY_MOD_FFI = 0

unix/time.c

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
#include <string.h>
2+
#include <time.h>
3+
4+
#include "misc.h"
5+
#include "mpconfig.h"
6+
#include "qstr.h"
7+
#include "obj.h"
8+
#include "runtime.h"
9+
10+
static mp_obj_t mod_time_time() {
11+
return mp_obj_new_int((machine_int_t)time(NULL));
12+
}
13+
static MP_DEFINE_CONST_FUN_OBJ_0(mod_time_time_obj, mod_time_time);
14+
15+
// Note: this is deprecated since CPy3.3, but pystone still uses it.
16+
static mp_obj_t mod_time_clock() {
17+
return mp_obj_new_int((machine_int_t)clock());
18+
}
19+
static MP_DEFINE_CONST_FUN_OBJ_0(mod_time_clock_obj, mod_time_clock);
20+
21+
void time_init() {
22+
mp_obj_t m = mp_obj_new_module(QSTR_FROM_STR_STATIC("time"));
23+
rt_store_attr(m, QSTR_FROM_STR_STATIC("time"), (mp_obj_t)&mod_time_time_obj);
24+
rt_store_attr(m, QSTR_FROM_STR_STATIC("clock"), (mp_obj_t)&mod_time_clock_obj);
25+
}

0 commit comments

Comments
 (0)