Search code examples
gtk3glib

How to monitor Gtk3 Event Loop latency


I would like to monitor Gtk3 event loop latency, i.e time spent for each iteration of Gtk main event loop. Basically, the idea is to run a custom function at each tick of the main event loop.

I tried g_idle_add, but documentation is not clear if the callback will be invoked at each loop.

Any thoughts ?


Solution

  • Probably writing a custom GSource is your best choice.

    GSource *
    g_source_new (GSourceFuncs *source_funcs,
                 guint struct_size);
    

    The size is specified to allow creating structures derived from GSource that contain additional data

    You should also give it the highest priority. I'm not sure it will be dispatched at every single iteration, but it will be prepared on every iteration. To bring your source to life you obtain context with g_main_loop_get_context and call g_source_attach.

    All in all it looks like this:

    // struct MySource
    // {
    //  struct GSource glib;
    //  int            my_data;
    // };
    
    
    gboolean my_prepare (GSource *source,
                         gint    *timeout_)
    {
      g_message ("%li", g_get_monotonic_time());
      *timeout_ = 0;
      (MySource*)source->my_data = 1;
      return TRUE;
    }
    
    
    GSourceFuncs funcs = {.prepare = my_prepare};
    
    GSource *src = g_source_new (&funcs, sizeof (MySource));
    g_source_set_priority (src, G_PRIORITY_HIGH);
    g_source_attach (src, g_main_loop_get_context());
    

    This doesn't include any cleanup.