module_timeit.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(timeit) {
15  KrkValue callable;
16  int times = 1000000;
17 
18  if (!krk_parseArgs("V|i", (const char *[]){"callable","number"},
19  &callable, &times)) {
20  return NONE_VAL();
21  }
22 
23  struct timeval tv_before, tv_after;
24  gettimeofday(&tv_before,NULL);
25  for (krk_integer_type t = 0; t < times; ++t) {
26  krk_push(callable);
27  krk_callStack(0);
28  if (unlikely(krk_currentThread.flags & KRK_THREAD_HAS_EXCEPTION)) return NONE_VAL();
29  }
30  gettimeofday(&tv_after,NULL);
31 
32  double before = (double)tv_before.tv_sec + (double)tv_before.tv_usec / 1000000.0;
33  double after = (double)tv_after.tv_sec + (double)tv_after.tv_usec / 1000000.0;
34 
35  return FLOATING_VAL(after-before);
36 }
37 
38 KrkValue krk_module_onload_timeit(void) {
39  KrkInstance * module = krk_newInstance(vm.baseClasses->moduleClass);
40  krk_push(OBJECT_VAL(module));
41 
42  KRK_DOC(module, "@brief Run functions very quickly without loop overhead from the interpreter.");
43 
44  BIND_FUNC(module,timeit);
45 
46  krk_pop();
47  return OBJECT_VAL(module);
48 }
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
int flags
Definition: vm.h:174
Stack reference or primative value.
Utilities for creating native bindings.
#define krk_parseArgs(f, n,...)
Parse arguments to a function while accepting keyword arguments.
Definition: util.h:348
#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.
KrkValue krk_callStack(int argCount)
Call a callable on the stack with argCount arguments.
Definition: vm.c:763
#define vm
Convenience macro for namespacing.
Definition: vm.h:267
KrkValue krk_pop(void)
Pop the top of the stack.
Definition: vm.c:170
threadLocal KrkThreadState krk_currentThread
Thread-local VM state.
void krk_push(KrkValue value)
Push a stack value.
Definition: vm.c:157