time.c
1 #include <assert.h>
2 #include <stdio.h>
3 #include <string.h>
4 #include <errno.h>
5 #include <unistd.h>
6 #include <time.h>
7 #include <sys/time.h>
8 
9 #include <kuroko/vm.h>
10 #include <kuroko/value.h>
11 #include <kuroko/object.h>
12 #include <kuroko/util.h>
13 
14 KRK_Function(sleep) {
15  FUNCTION_TAKES_EXACTLY(1);
16 
17  if (!IS_INTEGER(argv[0]) && !IS_FLOATING(argv[0])) {
18  return TYPE_ERROR(int or float,argv[0]);
19  }
20 
21  unsigned int usecs = (IS_INTEGER(argv[0]) ? AS_INTEGER(argv[0]) :
22  (IS_FLOATING(argv[0]) ? AS_FLOATING(argv[0]) : 0)) *
23  1000000;
24 
25  usleep(usecs);
26 
27  return BOOLEAN_VAL(1);
28 }
29 
30 KRK_Function(time) {
31  FUNCTION_TAKES_NONE();
32 
33  struct timeval tv;
34  gettimeofday(&tv,NULL);
35 
36  double out = (double)tv.tv_sec + (double)tv.tv_usec / 1000000.0;
37 
38  return FLOATING_VAL(out);
39 }
40 
42  KrkInstance * module = krk_newInstance(vm.baseClasses->moduleClass);
43  krk_attachNamedObject(&vm.modules, "time", (KrkObj*)module);
44  krk_attachNamedObject(&module->fields, "__name__", (KrkObj*)S("time"));
45  krk_attachNamedValue(&module->fields, "__file__", NONE_VAL());
46  KRK_DOC(module, "@brief Provides timekeeping functions.");
47  KRK_DOC(BIND_FUNC(module,sleep), "@brief Pause execution of the current thread.\n"
48  "@arguments secs\n\n"
49  "Uses the system @c usleep() function to sleep for @p secs seconds, which may be a @ref float or @ref int. "
50  "The available precision is platform-dependent.");
51  KRK_DOC(BIND_FUNC(module,time), "@brief Return the elapsed seconds since the system epoch.\n\n"
52  "Returns a @ref float representation of the number of seconds since the platform's epoch date. "
53  "On POSIX platforms, this is the number of seconds since 1 January 1970. "
54  "The precision of the return value is platform-dependent.");
55 }
56 
Struct definitions for core object types.
An object of a class.
Definition: object.h:255
KrkInstance * krk_newInstance(KrkClass *_class)
Create a new instance of the given class.
Definition: object.c:339
KrkTable fields
Attributes table.
Definition: object.h:258
The most basic object type.
Definition: object.h:41
void krk_attachNamedObject(KrkTable *table, const char name[], KrkObj *obj)
Attach an object to an attribute table.
Definition: vm.c:839
void krk_attachNamedValue(KrkTable *table, const char name[], KrkValue obj)
Attach a value to an attribute table.
Definition: vm.c:825
Utilities for creating native bindings.
#define KRK_DOC(thing, text)
Attach documentation to a thing of various types.
Definition: util.h:292
Definitions for primitive stack references.
Core API for the bytecode virtual machine.
#define vm
Convenience macro for namespacing.
Definition: vm.h:267
void krk_module_init_time(void)
Initialize the built-in 'time' module.
Definition: time.c:41