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.
This commit is contained in:
Kovid Goyal 2026-11-06 09:30:50 +05:30
parent 6c88ea3e37
commit 375c751dce
No known key found for this signature in database
GPG key ID: 06BC317B515ACE7C
11 changed files with 198 additions and 14 deletions

View file

@ -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;

View file

@ -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]

View file

@ -13,6 +13,7 @@
#include "data-types.h"
#include "font-select.h"
#include "state.h"
#include "startup-timing.h"
#include "threading.h"
#include <errno.h>
#include <fcntl.h>
@ -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

View file

@ -11,6 +11,7 @@
#include "dnd.h"
#include "charsets.h"
#include "control-codes.h"
#include "startup-timing.h"
#include <structmember.h>
#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();
}
}

View file

@ -9,6 +9,7 @@
#include "state.h"
#include "png-reader.h"
#include "threading.h"
#include "startup-timing.h"
#include <dlfcn.h>
#include <errno.h>
#include <stdint.h>
@ -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))

View file

@ -18,6 +18,7 @@
#include <limits.h>
#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;

View file

@ -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

View file

@ -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 <time.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
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 <time.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
monotonic_t monotonic_start_time = 0;
monotonic_t
monotonic_(void) {
return monotonic_clock_now();
}
int

View file

@ -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

107
kitty/startup-timing.c Normal file
View file

@ -0,0 +1,107 @@
/*
* startup-timing.c
* Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#include "data-types.h"
#include "startup-timing.h"
#include <stdarg.h>
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;
}

24
kitty/startup-timing.h Normal file
View file

@ -0,0 +1,24 @@
/*
* startup-timing.h
* Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
*
* 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 <stdbool.h>
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);