From 2eb2f9f554cd61d4f71a3eb945c89fdc53f4e62b Mon Sep 17 00:00:00 2001 From: Delyan Angelov Date: Sun, 22 Dec 2024 11:45:20 +0200 Subject: [PATCH] tools: add `v time`, to measure command execution time, in a cross platform way, without relying on other external tools --- cmd/tools/vtime.v | 39 ++++++++++++++++++++++++++++++++++++++ cmd/v/v.v | 1 + vlib/v/help/other/time.txt | 10 ++++++++++ 3 files changed, 50 insertions(+) create mode 100644 cmd/tools/vtime.v create mode 100644 vlib/v/help/other/time.txt diff --git a/cmd/tools/vtime.v b/cmd/tools/vtime.v new file mode 100644 index 0000000000..39c25b35bc --- /dev/null +++ b/cmd/tools/vtime.v @@ -0,0 +1,39 @@ +import os +import term +import time +import flag + +struct Context { +mut: + show_help bool + cmd_line_opts []string +} + +fn main() { + mut ctx := Context{} + args := arguments() + mut fp := flag.new_flag_parser(args#[1..]) + fp.application('v time') + fp.version('0.0.1') + fp.description('Start a command, and report how much time it took to run, and what its exit code was.') + fp.arguments_description('CMD [ARGS]') + fp.skip_executable() + fp.limit_free_args_to_at_least(1)! + ctx.show_help = fp.bool('help', `h`, false, 'Show this help screen.') + if ctx.show_help { + println(fp.usage()) + exit(0) + } + ctx.cmd_line_opts = fp.finalize() or { + eprintln('Error: ${err}') + exit(1) + } + cmd := ctx.cmd_line_opts.join(' ') + sw := time.new_stopwatch() + ecode := os.system(cmd) + elapsed := sw.elapsed() + stook_time := '${f64(elapsed.microseconds()) / 1000.0:8.3f} ms' + eprintln('> ${term.ecolorize(term.bright_yellow, stook_time)}. Exit code: ${ecode:3}. Command: ${term.ecolorize(term.green, + cmd)}') + exit(ecode) +} diff --git a/cmd/v/v.v b/cmd/v/v.v index 7632c89e02..b319955bc1 100644 --- a/cmd/v/v.v +++ b/cmd/v/v.v @@ -47,6 +47,7 @@ const external_tools = [ 'test-fmt', 'test-parser', 'test-self', + 'time', 'tracev', 'up', 'vet', diff --git a/vlib/v/help/other/time.txt b/vlib/v/help/other/time.txt new file mode 100644 index 0000000000..b84a2f1363 --- /dev/null +++ b/vlib/v/help/other/time.txt @@ -0,0 +1,10 @@ +v time 0.0.1 +----------------------------------------------- +Usage: v time [options] CMD [ARGS] + +Description: Start a command, and report how much time it took to run, and what its exit code was. + +The arguments should be at least 1 in number. + +Options: + -h, --help Show this help screen.