From 375c751dce8cc500cf8cb0d749457e4d3bb299cd Mon Sep 17 00:00:00 2001 From: Kovid Goyal Date: Fri, 6 Nov 2026 09:30:50 +0530 Subject: [PATCH] Add a --debug-startup command line flag Prints the time taken by the various phases of startup, measured from when the launcher started, including the time spent in the threads that load the GPU driver and select fonts and how long the main thread waited for them. Printing stops after the first frame is presented. --- kitty/data-types.c | 2 + kitty/fast_data_types.pyi | 2 + kitty/font-select.c | 6 ++ kitty/glfw.c | 5 ++ kitty/gpu.c | 5 ++ kitty/launcher/main.c | 9 +++ kitty/main.py | 14 +++++ kitty/monotonic.h | 31 ++++----- kitty/simple_cli_definitions.py | 7 +++ kitty/startup-timing.c | 107 ++++++++++++++++++++++++++++++++ kitty/startup-timing.h | 24 +++++++ 11 files changed, 198 insertions(+), 14 deletions(-) create mode 100644 kitty/startup-timing.c create mode 100644 kitty/startup-timing.h diff --git a/kitty/data-types.c b/kitty/data-types.c index b657ea5e5..bd8059f9e 100644 --- a/kitty/data-types.c +++ b/kitty/data-types.c @@ -902,6 +902,7 @@ extern bool init_crypto_library(PyObject *); extern bool init_desktop(PyObject *); extern bool init_fonts(PyObject *); extern bool init_font_select(PyObject *); +extern bool init_startup_timing(PyObject *); extern bool init_glfw(PyObject *m); extern bool init_dnd(PyObject *m); extern bool init_child(PyObject *m); @@ -979,6 +980,7 @@ PyInit_fast_data_types(void) { #endif if (!init_fonts(m)) return NULL; if (!init_font_select(m)) return NULL; + if (!init_startup_timing(m)) return NULL; if (!init_utmp(m)) return NULL; if (!init_loop_utils(m)) return NULL; if (!init_crypto_library(m)) return NULL; diff --git a/kitty/fast_data_types.pyi b/kitty/fast_data_types.pyi index 66384ba81..70f82e3f4 100644 --- a/kitty/fast_data_types.pyi +++ b/kitty/fast_data_types.pyi @@ -461,6 +461,8 @@ def start_font_selection( ) -> None: ... def finish_font_selection() -> FontSelectionResult: ... def variable_data_from_font_file(path: str, index: int = 0) -> VariableData: ... +def set_startup_timing(launch_time: int, python_initialized_time: int) -> None: ... +def startup_timing(msg: str) -> None: ... class FeatureData(TypedDict): name: NotRequired[str] diff --git a/kitty/font-select.c b/kitty/font-select.c index a9855b280..b0e81f375 100644 --- a/kitty/font-select.c +++ b/kitty/font-select.c @@ -13,6 +13,7 @@ #include "data-types.h" #include "font-select.h" #include "state.h" +#include "startup-timing.h" #include "threading.h" #include #include @@ -1686,12 +1687,15 @@ static struct { FSContext *ctx; pthread_t thread; bool thread_running; + monotonic_t started_at, finished_at; } pending = {0}; static void * selection_thread(void *x) { set_thread_name("KittyFontSelect"); + pending.started_at = monotonic_clock_now(); run_selection((FSContext *)x); + pending.finished_at = monotonic_clock_now(); return NULL; } @@ -1703,6 +1707,8 @@ wait_for_thread(void) { pending.thread_running = false; if (ret != 0) fatal("Failed to join the font selection thread with error: %s", strerror(ret)); debug_rendering("Waited %.2f ms for the font selection thread to finish\n", monotonic_t_to_s_double(monotonic() - start) * 1000); + startup_timing_thread("Font selection", pending.started_at, pending.finished_at); + startup_timing("Font selection finished, waited %.2f ms for it", monotonic_t_to_s_double(monotonic() - start) * 1000); } void diff --git a/kitty/glfw.c b/kitty/glfw.c index 41b8598f8..19669016e 100644 --- a/kitty/glfw.c +++ b/kitty/glfw.c @@ -11,6 +11,7 @@ #include "dnd.h" #include "charsets.h" #include "control-codes.h" +#include "startup-timing.h" #include #include "glfw-wrapper.h" #ifdef __APPLE__ @@ -2371,6 +2372,7 @@ create_os_window(PyObject UNUSED *self, PyObject *args, PyObject *kw) { PyErr_Format(PyExc_RuntimeError, "Failed to load a GPU driver:\n%s", err); return NULL; } + startup_timing("GPU driver loaded"); } int x = INT_MIN, y = INT_MIN, window_state = WINDOW_NORMAL, disallow_override_title = 0; char *wm_class_class, *wm_class_name; @@ -2551,6 +2553,7 @@ create_os_window(PyObject UNUSED *self, PyObject *args, PyObject *kw) { get_window_content_scale(temp_window, &xscale, &yscale, &xdpi, &ydpi); } FONTS_DATA_HANDLE fonts_data = load_fonts_data(OPT(font_size), xdpi, ydpi); + startup_timing("Fonts loaded"); PyObject *ret = PyObject_CallFunction( get_window_size, "IIddff", @@ -2646,6 +2649,7 @@ create_os_window(PyObject UNUSED *self, PyObject *args, PyObject *kw) { PyObject *ret = PyObject_CallNoArgs(load_programs); if (ret == NULL) return NULL; Py_DECREF(ret); + startup_timing("Shaders loaded"); get_platform_dependent_config_values(glfw_window); if (!global_state.supports_framebuffer_srgb) { log_error("The OpenGL drivers dont support GL_FRAMEBUFFER_SRGB this will cause a small rendering performance penalty"); @@ -3464,6 +3468,7 @@ swap_window_buffers(OSWindow *os_window) { log_error("Failed to present the GPU surface of OS Window: %llu with error: %s", os_window->id, gpu_last_error()); glfwWindowContentsPresented(os_window->handle); os_window->keep_rendering_till_swap = 0; + startup_timing_frame_presented(); } } diff --git a/kitty/gpu.c b/kitty/gpu.c index 62536e42c..470a2dc73 100644 --- a/kitty/gpu.c +++ b/kitty/gpu.c @@ -9,6 +9,7 @@ #include "state.h" #include "png-reader.h" #include "threading.h" +#include "startup-timing.h" #include #include #include @@ -182,12 +183,15 @@ static struct { char errbuf[8192]; size_t pos; bool loaded, failed; + monotonic_t started_at, finished_at; } async_load = {0}; static void * async_load_thread(void *x UNUSED) { set_thread_name("KittyGPULoad"); + async_load.started_at = monotonic_clock_now(); async_load.loaded = load_gpu_driver_candidates(&async_load.display, 1, async_load.errbuf, sizeof(async_load.errbuf), &async_load.pos); + async_load.finished_at = monotonic_clock_now(); return NULL; } @@ -216,6 +220,7 @@ wait_for_gpu_driver(void) { async_load.pending = false; if (ret != 0) fatal("Failed to join the thread loading the GPU driver with error: %s", strerror(ret)); if (candidates.debug_rendering) timed_debug_print("Finished waiting for the GPU driver to load\n"); + startup_timing_thread("Loading the GPU driver", async_load.started_at, async_load.finished_at); if (async_load.loaded) return NULL; // Try the remaining candidates, appending to the reasons the first failed if (has_untried_gpu_drivers() && load_gpu_driver_candidates(&async_load.display, SIZE_MAX, async_load.errbuf, sizeof(async_load.errbuf), &async_load.pos)) diff --git a/kitty/launcher/main.c b/kitty/launcher/main.c index 9cb98c6cf..0161870a8 100644 --- a/kitty/launcher/main.c +++ b/kitty/launcher/main.c @@ -18,6 +18,7 @@ #include #endif #include "launcher.h" +#include "../monotonic.h" #include "utils.h" #define FOR_LAUNCHER #include "cli-parser-data_generated.h" @@ -47,6 +48,9 @@ safe_realpath(const char *src, char *buf, size_t buf_sz) { } #endif +// The time at which the launcher started, used by --debug-startup +static monotonic_t launch_time = 0; + typedef struct { const char *exe, *exe_dir, *lc_ctype, *lib_dir, *config_dir; CLISpec *cli_spec; @@ -121,6 +125,10 @@ set_kitty_run_data(RunData *run_data, bool from_source, wchar_t *extensions_dir) return false; } S(cli_flags, cli_flags); + PyObject *lt = PyLong_FromLongLong(launch_time); + S(launch_time, lt); + PyObject *pit = PyLong_FromLongLong(monotonic_clock_now()); + S(python_initialized_time, pit); #undef S int ret = PySys_SetObject("kitty_run_data", ans); @@ -567,6 +575,7 @@ output_test_data(RunData *rd) { int main(int argc_, char *argv_[], char *envp[]) { + launch_time = monotonic_clock_now(); if (argc_ < 1 || !argv_) { fprintf(stderr, "Invalid argc/argv\n"); return 1; diff --git a/kitty/main.py b/kitty/main.py index e18eca753..792792578 100644 --- a/kitty/main.py +++ b/kitty/main.py @@ -54,7 +54,9 @@ from .fast_data_types import ( set_custom_cursor, set_default_window_icon, set_options, + set_startup_timing, set_use_os_log, + startup_timing, ) from .fonts.render import dump_font_debug, set_font_family from .logout_session import ( @@ -321,6 +323,7 @@ def _run_app(opts: Options, args: CLIOptions, bad_lines: Sequence[BadLine] = (), from .boss import Boss from .session import create_sessions, get_os_window_sizing_data + startup_timing('Imported the boss and session modules') global _is_panel_kitten _is_panel_kitten = run_app.cached_values_name == 'panel' if _is_panel_kitten and run_app.layer_shell_config and run_app.layer_shell_config.output_name in ('list', 'listjson'): @@ -352,6 +355,7 @@ def _run_app(opts: Options, args: CLIOptions, bad_lines: Sequence[BadLine] = (), if getattr(args, 'session', ''): args.session = '' startup_sessions = tuple(create_sessions(opts, args)) + startup_timing('Startup sessions created') if not _is_panel_kitten and not is_wayland(): if opts.remember_window_position: cached_workarea = tuple(tuple(x) for x in cached_values.get('monitor-workarea', ())) @@ -388,8 +392,10 @@ def _run_app(opts: Options, args: CLIOptions, bad_lines: Sequence[BadLine] = (), x=pos_x, y=pos_y, ) + startup_timing('First OS Window created') boss = Boss(opts, args, cached_values, global_shortcuts, talk_fd) boss.start(window_id, startup_sessions) + startup_timing('Boss created and started') if restored is not None: try: finish_restore(restored.path) @@ -414,6 +420,7 @@ def _run_app(opts: Options, args: CLIOptions, bad_lines: Sequence[BadLine] = (), # that they are not repeatedly scanned and re-enable it. gc.freeze() gc.enable() + startup_timing('Entering the main loop') try: boss.child_monitor.main_loop() finally: @@ -435,6 +442,7 @@ class AppRunner: # Fonts are selected in a thread, while the rest of startup happens, # the results are used when the first OS Window is created set_font_family(opts, add_builtin_nerd_font=True, threaded=True) + startup_timing('Font selection started') _run_app(opts, args, bad_lines, talk_fd) finally: set_options(None) @@ -659,6 +667,10 @@ def kitty_main(called_from_panel: bool = False) -> None: cli_opts.args = [] else: cli_opts.args = rest + if cli_opts.debug_startup: + krd = getattr(sys, 'kitty_run_data', {}) + set_startup_timing(krd.get('launch_time', 0), krd.get('python_initialized_time', 0)) + startup_timing('Command line parsed') talk_fd = -1 if cli_opts.single_instance: si_data = os.environ.pop('KITTY_SI_DATA', '') @@ -678,6 +690,7 @@ def kitty_main(called_from_panel: bool = False) -> None: set_ignore_config_dir_files('NONE' in cli_opts.config) bad_lines: list[BadLine] = [] opts = create_opts(cli_opts, accumulate_bad_lines=bad_lines) + startup_timing('Configuration loaded') if is_quick_access_terminal_app: opts.macos_hide_from_tasks = True setup_environment(opts, cli_opts) @@ -701,6 +714,7 @@ def kitty_main(called_from_panel: bool = False) -> None: # kitty can handle them. See https://github.com/kovidgoyal/kitty/issues/4636 mask_kitty_signals_process_wide() init_glfw(opts, cli_opts.debug_keyboard, cli_opts.debug_rendering) + startup_timing('GLFW initialized') try: with setup_profiling(): # Avoid needing to launch threads to reap zombies diff --git a/kitty/monotonic.h b/kitty/monotonic.h index 00ce9518b..e4737838d 100644 --- a/kitty/monotonic.h +++ b/kitty/monotonic.h @@ -74,21 +74,11 @@ init_monotonic(void) { extern int timed_debug_print(const char *fmt, ...) __attribute__((format(printf, 1, 2))); -#ifdef MONOTONIC_IMPLEMENTATION +// The current time of the clock used by monotonic(). This is used by both the +// launcher and the fast_data_types module so that times can be compared. #include -#include -#include -#include - -monotonic_t monotonic_start_time = 0; - static inline monotonic_t -calc_nano_time(struct timespec time) { - return ((monotonic_t)time.tv_sec * MONOTONIC_T_1e9) + (monotonic_t)time.tv_nsec; -} - -monotonic_t -monotonic_(void) { +monotonic_clock_now(void) { struct timespec ts = {0}; #ifdef CLOCK_HIGHRES clock_gettime(CLOCK_HIGHRES, &ts); @@ -97,7 +87,20 @@ monotonic_(void) { #else clock_gettime(CLOCK_MONOTONIC, &ts); #endif - return calc_nano_time(ts); + return ((monotonic_t)ts.tv_sec * MONOTONIC_T_1e9) + (monotonic_t)ts.tv_nsec; +} + +#ifdef MONOTONIC_IMPLEMENTATION +#include +#include +#include +#include + +monotonic_t monotonic_start_time = 0; + +monotonic_t +monotonic_(void) { + return monotonic_clock_now(); } int diff --git a/kitty/simple_cli_definitions.py b/kitty/simple_cli_definitions.py index 5b6cd9832..c35a61016 100644 --- a/kitty/simple_cli_definitions.py +++ b/kitty/simple_cli_definitions.py @@ -550,6 +550,13 @@ Print out information about the selection of fallback fonts for characters not present in the main font. +--debug-startup +type=bool-set +Print out the time taken by the various phases of startup, such as loading the +configuration, selecting fonts, loading the GPU driver and creating the first +OS Window. Times are measured from when the {appname} process started. + + --watcher completion=type:file ext:py relative:conf group:"Watcher files" This option is deprecated in favor of the :opt:`watcher` option in diff --git a/kitty/startup-timing.c b/kitty/startup-timing.c new file mode 100644 index 000000000..9623e6b50 --- /dev/null +++ b/kitty/startup-timing.c @@ -0,0 +1,107 @@ +/* + * startup-timing.c + * Copyright (C) 2026 Kovid Goyal + * + * Distributed under terms of the GPL3 license. + */ + +#include "data-types.h" +#include "startup-timing.h" +#include + +static struct { + bool enabled; + monotonic_t launch_time, previous; +} st = {0}; + +static double +as_ms(monotonic_t t) { + return (double)t / 1e6; +} + +bool +startup_timing_enabled(void) { + return st.enabled; +} + +static void +vprint(monotonic_t at, const char *fmt, va_list args) { + fprintf(stderr, "[startup] %8.2f ms (+%7.2f ms) ", as_ms(at - st.launch_time), as_ms(at - st.previous)); + vfprintf(stderr, fmt, args); + fputc('\n', stderr); + fflush(stderr); + st.previous = at; +} + +static void +print_at(monotonic_t at, const char *fmt, ...) { + va_list args; + va_start(args, fmt); + vprint(at, fmt, args); + va_end(args); +} + +void +startup_timing(const char *fmt, ...) { + if (!st.enabled) return; + const monotonic_t now = monotonic_clock_now(); + va_list args; + va_start(args, fmt); + vprint(now, fmt, args); + va_end(args); +} + +void +startup_timing_thread(const char *name, monotonic_t start, monotonic_t end) { + if (!st.enabled) return; + fprintf( + stderr, + "[startup] %s ran in a thread from %.2f ms to %.2f ms, taking %.2f ms\n", + name, + as_ms(start - st.launch_time), + as_ms(end - st.launch_time), + as_ms(end - start)); + fflush(stderr); +} + +void +startup_timing_frame_presented(void) { + if (!st.enabled) return; + startup_timing("First frame presented"); + st.enabled = false; +} + +static PyObject * +set_startup_timing(PyObject *self UNUSED, PyObject *args) { + long long launch_time = 0, python_initialized_time = 0; + if (!PyArg_ParseTuple(args, "LL", &launch_time, &python_initialized_time)) return NULL; + st.enabled = true; + // Without times from the launcher, use the time at which this module was loaded + const bool has_launch_time = launch_time > 0; + st.launch_time = has_launch_time ? launch_time : monotonic_start_time; + st.previous = st.launch_time; + if (has_launch_time) { + print_at(st.launch_time, "Process started"); + if (python_initialized_time > 0) print_at(python_initialized_time, "Python interpreter initialized"); + } else print_at(st.launch_time, "The fast_data_types module was loaded, the process start time is unknown"); + Py_RETURN_NONE; +} + +static PyObject * +py_startup_timing(PyObject *self UNUSED, PyObject *msg) { + if (!PyUnicode_Check(msg)) { + PyErr_SetString(PyExc_TypeError, "msg must be a string"); + return NULL; + } + if (st.enabled) startup_timing("%s", PyUnicode_AsUTF8(msg)); + Py_RETURN_NONE; +} + +static PyMethodDef module_methods[] = { + METHODB(set_startup_timing, METH_VARARGS), {"startup_timing", (PyCFunction)py_startup_timing, METH_O, ""}, {NULL, NULL, 0, NULL} /* Sentinel */ +}; + +bool +init_startup_timing(PyObject *module) { + return PyModule_AddFunctions(module, module_methods) == 0; +} diff --git a/kitty/startup-timing.h b/kitty/startup-timing.h new file mode 100644 index 000000000..be2ac910f --- /dev/null +++ b/kitty/startup-timing.h @@ -0,0 +1,24 @@ +/* + * startup-timing.h + * Copyright (C) 2026 Kovid Goyal + * + * Distributed under terms of the GPL3 license. + */ + +#pragma once + +// Printing of the time taken by the phases of startup, for --debug-startup. +// Times are from monotonic_clock_now() and are printed relative to when the +// process started. Must only be called from the main thread, work done in +// other threads is reported with startup_timing_thread(). Printing stops +// after the first frame is presented. + +#include "monotonic.h" +#include + +bool startup_timing_enabled(void); +void startup_timing(const char *fmt, ...) __attribute__((format(printf, 1, 2))); +// Report work done in a thread between start and end +void startup_timing_thread(const char *name, monotonic_t start, monotonic_t end); +// Called when a frame is presented, reports the first one and stops printing +void startup_timing_frame_presented(void);