2

I am trying to load time.h directly with Cython instead of Python's import time but it doesn't work.

All I get is an error

Call with wrong number of arguments (expected 1, got 0)

with the following code

cdef extern from "time.h" nogil:
    ctypedef int time_t
    time_t time(time_t*)

def test():
    cdef int ts
    ts = time()


    return ts

and

Cannot assign type 'long' to 'time_t *'

with the following code

cdef extern from "time.h" nogil:
    ctypedef int time_t
    time_t time(time_t*)

def test():
    cdef int ts
    ts = time(1)


    return ts

with math log I can simply do

cdef extern from "math.h":
    double log10(double x)

How comes it is not possible with time?

P. Camilleri
  • 12,664
  • 7
  • 41
  • 76
Adam Barak
  • 67
  • 1
  • 14

2 Answers2

5

The parameter to time is the address (i.e.: "pointer") of a time_t value to fill or NULL.

To quote man 2 time:

time_t time(time_t *t);

[...]

If t is non-NULL, the return value is also stored in the memory pointed to by t.

It is an oddity of some standard functions to both return a value and (possibly) store the same value in a provided address. It is perfectly safe to pass 0 as parameter as in most architecture NULL is equivalent to ((void*)0). In that case, time will only return the result, and will not attempt to store it in the provided address.

Sylvain Leroux
  • 50,096
  • 7
  • 103
  • 125
  • From what I understand *NULL* should almost always be used unless you're storing the result. In my case I don't need to store it so it's fine. Nice explanation by the way :) – Adam Barak Aug 27 '14 at 17:45
2

Pass in NULL to time. Also you can use the builtin libc.time:

from libc.time cimport time,time_t

cdef time_t t = time(NULL)
print t

which gives

1471622065
frmdstryr
  • 20,142
  • 3
  • 38
  • 32
  • is this in seconds or nanoseconds ? Where is the documentation of cimport time ? – Sylvain Apr 30 '21 at 15:20
  • @Sylvain this uses `time` from `libc`. You can find docs by googling libc time. You should end up at the [libc docs here](https://www.gnu.org/software/libc/manual/html_node/Getting-the-Time.html). The `time_t` type is defined in [libc docs here](https://www.gnu.org/software/libc/manual/html_node/Time-Types.html). You can also see how the libc time library is wrapped by Cython in the Cython source code [here](https://github.com/cython/cython/blob/master/Cython/Includes/cpython/time.pxd). – Justin Lanfranchi May 17 '23 at 14:25