Subject: Re: bug#65700: time when gcs-done is updated needs to be clarified

From: Stefan Monnier <[email-masked]>
Date: Thu, 07 Sep 2023 09:38:35 -0400

>> I wrote a function which runs each time Emacs collects garbage, so I
>> added it to `post-gc-hook'.
>> 
>> That function cares about the value of `gcs-done' and the value of
>> `gc-elapsed'.  But it seems that `gcs-done' is updated after
>> `post-gc-hook' is executed?

Indeed, from what I see in the code, `gc-elapsed` and `gcs-done` are
updated *after* running `post-gc-hook`.
This means for example that the time to run `post-gc-hook` is included
in the `gc-elapsed` time.

>> Is this an intended behavior?

Good question.  AFAICT this was added by the following commit:

    commit 2c5bd60800ce4f2702f263eda2145be342208ffe
    Author: Dave Love <[email-masked]>
    Date:   Thu Jan 30 14:15:58 2003 +0000
    
        (Vgc_elapsed, gcs_done): New variables.
        (Fgarbage_collect): Use them.
        (init_alloc, syms_of_alloc): Set them up.
    
    diff --git a/src/alloc.c b/src/alloc.c
    --- a/src/alloc.c
    +++ b/src/alloc.c
    @@ -4367,7 +4373,15 @@
       if (!NILP (Vpost_gc_hook))
         {
           int count = inhibit_garbage_collection ();
           safe_run_hooks (Qpost_gc_hook);
           unbind_to (count, Qnil);
         }
    -  
    +
    +  /* Accumulate statistics.  */
    +  EMACS_GET_TIME (t2);
    +  EMACS_SUB_TIME (t3, t2, t1);
    +  if (FLOATP (Vgc_elapsed))
    +    XSETFLOAT (Vgc_elapsed, make_float (XFLOAT_DATA (Vgc_elapsed) +
    +					EMACS_SECS (t3) +
    +					EMACS_USECS (t3) * 1.0e-6));
    +  gcs_done++;

The only related commit I see around that time is the associated NEWS
message:

    ** New variables `gc-elapsed' and `gcs-done' provide extra information
    on garbage collection.

So I strongly suspect that it was largely accidental.  "Philosophically",
both choices make sense (either consider `post-gc-hook` as being part of
the GC or consider it as external to the GC).

I'd be curious to know how it affects your code.

        Stefan