|
| 1 | +/* |
| 2 | + * Copyright (C) 2024 Nicolai Brand (https://lytix.dev) |
| 3 | + * |
| 4 | + * This program is free software: you can redistribute it and/or modify |
| 5 | + * it under the terms of the GNU General Public License as published by |
| 6 | + * the Free Software Foundation, either version 3 of the License, or |
| 7 | + * (at your option) any later version. |
| 8 | + * |
| 9 | + * This program is distributed in the hope that it will be useful, |
| 10 | + * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 | + * GNU General Public License for more details. |
| 13 | + * |
| 14 | + * You should have received a copy of the GNU General Public License |
| 15 | + * along with this program. If not, see <https://www.gnu.org/licenses/>. |
| 16 | + */ |
| 17 | + |
| 18 | +#include <stdio.h> |
| 19 | +#include <sys/resource.h> |
| 20 | +#include <time.h> |
| 21 | + |
| 22 | +#include "interpreter/exec.h" |
| 23 | +#include "interpreter/interpreter.h" |
| 24 | +#include "interpreter/value/slash_str.h" |
| 25 | +#include "interpreter/value/slash_value.h" |
| 26 | + |
| 27 | + |
| 28 | +int builtin_time(Interpreter *interpreter, size_t argc, SlashValue *argv) |
| 29 | +{ |
| 30 | + struct rusage start_usage; |
| 31 | + getrusage(RUSAGE_SELF, &start_usage); |
| 32 | + clock_t start_time = clock(); |
| 33 | + |
| 34 | + char *exec_argv[argc + 1]; // + 1 because last element is NULL |
| 35 | + exec_argv[argc] = NULL; |
| 36 | + gc_barrier_start(&interpreter->gc); |
| 37 | + |
| 38 | + for (size_t i = 0; i < argc; i++) { |
| 39 | + SlashValue arg = argv[i]; |
| 40 | + VERIFY_TRAIT_IMPL(to_str, arg, "Could not take 'to_str' of type '%s'", arg.T->name); |
| 41 | + SlashValue value_str_repr = arg.T->to_str(interpreter, arg); |
| 42 | + exec_argv[i] = AS_STR(value_str_repr)->str; |
| 43 | + } |
| 44 | + |
| 45 | + gc_barrier_end(&interpreter->gc); |
| 46 | + int exit_code = exec_program(&interpreter->stream_ctx, exec_argv); |
| 47 | + |
| 48 | + struct rusage end_usage; |
| 49 | + getrusage(RUSAGE_CHILDREN, &end_usage); |
| 50 | + clock_t end_time = clock(); |
| 51 | + |
| 52 | + double real_time = (double)(end_time - start_time) / CLOCKS_PER_SEC; |
| 53 | + double user_time = (double)(end_usage.ru_utime.tv_sec + end_usage.ru_utime.tv_usec / 1000000.0); |
| 54 | + double sys_time = (double)(end_usage.ru_stime.tv_sec + end_usage.ru_stime.tv_usec / 1000000.0); |
| 55 | + printf("real\t%.3f\n", real_time); |
| 56 | + printf("user\t%.3f\n", user_time); |
| 57 | + printf("sys\t%.3f\n", sys_time); |
| 58 | + |
| 59 | + return exit_code; |
| 60 | +} |
0 commit comments