7c1dbaf946b199d98a5b3d4f01c2d75d24769c73
[ghc-hetmet.git] / ghc / rts / Stats.c
1 /* -----------------------------------------------------------------------------
2  *
3  * (c) The GHC Team, 1998-2004
4  *
5  * Statistics and timing-related functions.
6  *
7  * ---------------------------------------------------------------------------*/
8
9 /* Alas, no.  This source is non-posix.
10    #include "PosixSource.h" 
11 */
12
13 #include "Rts.h"
14 #include "RtsFlags.h"
15 #include "RtsUtils.h"
16 #include "MBlock.h"
17 #include "Schedule.h"
18 #include "Stats.h"
19 #include "ParTicky.h"                       /* ToDo: move into Rts.h */
20 #include "Profiling.h"
21 #include "Storage.h"
22
23 #ifdef HAVE_UNISTD_H
24 #include <unistd.h>
25 #endif
26
27 #ifndef mingw32_HOST_OS
28 # ifdef HAVE_SYS_TIMES_H
29 #  include <sys/times.h>
30 # endif
31 #endif
32
33 #ifdef HAVE_SYS_TIME_H
34 #include <sys/time.h>
35 #endif
36
37 #ifdef __CYGWIN32__
38 # ifdef HAVE_TIME_H
39 #  include <time.h>
40 # endif
41 #endif
42
43 #if ! irix_HOST_OS && ! defined(mingw32_HOST_OS)
44 # if defined(HAVE_SYS_RESOURCE_H)
45 #  include <sys/resource.h>
46 # endif
47 #endif
48
49 #ifdef HAVE_SYS_TIMEB_H
50 #include <sys/timeb.h>
51 #endif
52
53 #if HAVE_STDLIB_H
54 #include <stdlib.h>
55 #endif
56
57 #if HAVE_WINDOWS_H
58 #include <windows.h>
59 #endif
60
61 #if defined(PAR) || !(!defined(HAVE_GETRUSAGE) || irix_HOST_OS || defined(mingw32_HOST_OS) || defined(cygwin32_HOST_OS))
62 #include <sys/resource.h>
63 #endif
64
65 /* huh? */
66 #define BIG_STRING_LEN              512
67
68 /* We're not trying to be terribly accurate here, using the 
69  * basic times() function to get a resolution of about 100ths of a 
70  * second, depending on the OS.  A long int will do fine for holding
71  * these values.
72  */
73 #define TICK_TYPE long int
74 #define TICK_TO_DBL(t) ((double)(t) / TicksPerSecond)
75
76 static int TicksPerSecond = 0;
77
78 static TICK_TYPE ElapsedTimeStart = 0;
79 static TICK_TYPE CurrentElapsedTime = 0;
80 static TICK_TYPE CurrentUserTime    = 0;
81
82 static TICK_TYPE InitUserTime     = 0;
83 static TICK_TYPE InitElapsedTime  = 0;
84 static TICK_TYPE InitElapsedStamp = 0;
85
86 static TICK_TYPE MutUserTime      = 0;
87 static TICK_TYPE MutElapsedTime   = 0;
88 static TICK_TYPE MutElapsedStamp  = 0;
89
90 static TICK_TYPE ExitUserTime     = 0;
91 static TICK_TYPE ExitElapsedTime  = 0;
92
93 static ullong GC_tot_alloc        = 0;
94 static ullong GC_tot_copied       = 0;
95
96 static TICK_TYPE GC_start_time = 0,  GC_tot_time  = 0;  /* User GC Time */
97 static TICK_TYPE GCe_start_time = 0, GCe_tot_time = 0;  /* Elapsed GC time */
98
99 #ifdef PROFILING
100 static TICK_TYPE RP_start_time  = 0, RP_tot_time  = 0;  /* retainer prof user time */
101 static TICK_TYPE RPe_start_time = 0, RPe_tot_time = 0;  /* retainer prof elap time */
102
103 static TICK_TYPE HC_start_time, HC_tot_time = 0;     // heap census prof user time
104 static TICK_TYPE HCe_start_time, HCe_tot_time = 0;   // heap census prof elap time
105 #endif
106
107 #ifdef PROFILING
108 #define PROF_VAL(x)   (x)
109 #else
110 #define PROF_VAL(x)   0
111 #endif
112
113 static lnat MaxResidency = 0;     // in words; for stats only
114 static lnat AvgResidency = 0;
115 static lnat ResidencySamples = 0; // for stats only
116
117 static lnat GC_start_faults = 0, GC_end_faults = 0;
118
119 static TICK_TYPE *GC_coll_times;
120
121 static void  getTimes(void);
122 static nat   pageFaults(void);
123
124 static void statsPrintf( char *s, ... );
125 static void statsFlush( void );
126 static void statsClose( void );
127
128 /* elapsedtime() -- The current elapsed time in seconds */
129
130 #if defined(mingw32_HOST_OS) || defined(cygwin32_HOST_OS)
131 #define HNS_PER_SEC 10000000LL /* FILETIMES are in units of 100ns */
132 /* Convert FILETIMEs into secs */
133 #define FT2longlong(ll,ft)    \
134     (ll)=(ft).dwHighDateTime; \
135     (ll) <<= 32;              \
136     (ll) |= (ft).dwLowDateTime; \
137     (ll) /= (unsigned long long) (HNS_PER_SEC / CLOCKS_PER_SEC)
138 #endif
139
140 #if defined(mingw32_HOST_OS) || defined(cygwin32_HOST_OS)
141 /* cygwin32 or mingw32 version */
142 static void
143 getTimes(void)
144 {
145     static int is_win9x = -1;
146
147     FILETIME creationTime, exitTime, userTime, kernelTime = {0,0};
148     long long int kT, uT;
149     
150     if (is_win9x < 0) {
151       /* figure out whether we're on a Win9x box or not. */
152       OSVERSIONINFO oi;
153       BOOL b;
154
155       /* Need to init the size field first.*/
156       oi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
157       b = GetVersionEx(&oi);
158       
159       is_win9x = ( (b && (oi.dwPlatformId & VER_PLATFORM_WIN32_WINDOWS)) ? 1 : 0);
160     }
161  
162     if (is_win9x) {
163       /* On Win9x, just attribute all running time to the user. */
164       SYSTEMTIME st;
165
166       GetSystemTime(&st);
167       SystemTimeToFileTime(&st,&userTime);
168     } else {
169       /* ToDo: pin down elapsed times to just the OS thread(s) that
170          are evaluating/managing Haskell code.
171       */
172       if (!GetProcessTimes (GetCurrentProcess(), &creationTime,
173                           &exitTime, &kernelTime, &userTime)) {
174         /* Probably on a Win95 box..*/
175         CurrentElapsedTime = 0;
176         CurrentUserTime = 0;
177         return;
178       }
179     }
180
181     FT2longlong(kT,kernelTime);
182     FT2longlong(uT,userTime);
183     CurrentElapsedTime = uT + kT;
184     CurrentUserTime = uT;
185
186     if (is_win9x) {
187       /* Adjust for the fact that we're using system time & not
188          process time on Win9x. */
189       CurrentUserTime    -= ElapsedTimeStart;
190       CurrentElapsedTime -= ElapsedTimeStart;
191     }
192 }
193
194 #else /* !win32 */
195
196 static void
197 getTimes(void)
198 {
199
200 #ifndef HAVE_TIMES
201     /* We will #ifdef around the fprintf for machines
202        we *know* are unsupported. (WDP 94/05)
203     */
204     debugBelch("NOTE: `getTimes' does nothing!\n");
205     return 0.0;
206
207 #else /* not stumped */
208     struct tms t;
209     clock_t r = times(&t);
210
211     CurrentElapsedTime = r;
212     CurrentUserTime = t.tms_utime;
213 #endif
214
215 }
216 #endif /* !win32 */
217
218 /* mut_user_time_during_GC() and mut_user_time()
219  *
220  * The former function can be used to get the current mutator time
221  * *during* a GC, i.e. between stat_startGC and stat_endGC.  This is
222  * used in the heap profiler for accurately time stamping the heap
223  * sample.  
224  *
225  * ATTENTION: mut_user_time_during_GC() relies on GC_start_time being 
226  *            defined in stat_startGC() - to minimise system calls, 
227  *            GC_start_time is, however, only defined when really needed (check
228  *            stat_startGC() for details)
229  */
230 double
231 mut_user_time_during_GC( void )
232 {
233   return TICK_TO_DBL(GC_start_time - GC_tot_time - PROF_VAL(RP_tot_time + HC_tot_time));
234 }
235
236 double
237 mut_user_time( void )
238 {
239     getTimes();
240     return TICK_TO_DBL(CurrentUserTime - GC_tot_time - PROF_VAL(RP_tot_time + HC_tot_time));
241 }
242
243 #ifdef PROFILING
244 /*
245   mut_user_time_during_RP() is similar to mut_user_time_during_GC();
246   it returns the MUT time during retainer profiling.
247   The same is for mut_user_time_during_HC();
248  */
249 double
250 mut_user_time_during_RP( void )
251 {
252   return TICK_TO_DBL(RP_start_time - GC_tot_time - RP_tot_time - HC_tot_time);
253 }
254
255 double
256 mut_user_time_during_heap_census( void )
257 {
258   return TICK_TO_DBL(HC_start_time - GC_tot_time - RP_tot_time - HC_tot_time);
259 }
260 #endif /* PROFILING */
261
262 static nat
263 pageFaults(void)
264 {
265   /* ToDo (on NT): better, get this via the performance data
266      that's stored in the registry. */
267 # if !defined(HAVE_GETRUSAGE) || irix_HOST_OS || defined(mingw32_HOST_OS) || defined(cygwin32_HOST_OS)
268     return 0;
269 # else
270     struct rusage t;
271
272     getrusage(RUSAGE_SELF, &t);
273     return(t.ru_majflt);
274 # endif
275 }
276
277 void
278 initStats(void)
279 {
280     nat i;
281   
282     if (RtsFlags.GcFlags.giveStats >= VERBOSE_GC_STATS) {
283         statsPrintf("    Alloc    Collect    Live    GC    GC     TOT     TOT  Page Flts\n");
284         statsPrintf("    bytes     bytes     bytes  user  elap    user    elap\n");
285     }
286     GC_coll_times = 
287         (TICK_TYPE *)stgMallocBytes(
288             sizeof(TICK_TYPE)*RtsFlags.GcFlags.generations,
289             "initStats");
290     for (i = 0; i < RtsFlags.GcFlags.generations; i++) {
291         GC_coll_times[i] = 0;
292     }
293 }    
294
295 /* -----------------------------------------------------------------------------
296    Initialisation time...
297    -------------------------------------------------------------------------- */
298
299 void
300 stat_startInit(void)
301 {
302     /* Determine TicksPerSecond ... */
303 #if defined(CLK_TCK)            /* defined by POSIX */
304     TicksPerSecond = CLK_TCK;
305
306 #elif defined(HAVE_SYSCONF)
307     long ticks;
308
309     ticks = sysconf(_SC_CLK_TCK);
310     if ( ticks == -1 ) {
311         debugBelch("stat_init: bad call to 'sysconf'!\n");
312         stg_exit(EXIT_FAILURE);
313     }
314     TicksPerSecond = ticks;
315
316 /* no "sysconf" or CLK_TCK; had better guess */
317 #elif defined(HZ)
318     TicksPerSecond = HZ;
319
320 #elif defined(CLOCKS_PER_SEC)
321     TicksPerSecond = CLOCKS_PER_SEC;
322
323 #else /* had better guess wildly */
324     /* We will #ifdef around the fprintf for machines
325        we *know* are unsupported. (WDP 94/05)
326     */
327     debugBelch("NOTE: Guessing `TicksPerSecond = 60'!\n");
328     TicksPerSecond = 60;
329 #endif
330
331     getTimes();
332     ElapsedTimeStart = CurrentElapsedTime;
333 }
334
335 void 
336 stat_endInit(void)
337 {
338     getTimes();
339     InitUserTime = CurrentUserTime;
340     InitElapsedStamp = CurrentElapsedTime; 
341     if (ElapsedTimeStart > CurrentElapsedTime) {
342         InitElapsedTime = 0;
343     } else {
344         InitElapsedTime = CurrentElapsedTime - ElapsedTimeStart;
345     }
346 }
347
348 /* -----------------------------------------------------------------------------
349    stat_startExit and stat_endExit
350    
351    These two measure the time taken in shutdownHaskell().
352    -------------------------------------------------------------------------- */
353
354 void
355 stat_startExit(void)
356 {
357     getTimes();
358     MutElapsedStamp = CurrentElapsedTime;
359     MutElapsedTime = CurrentElapsedTime - GCe_tot_time -
360         PROF_VAL(RPe_tot_time + HCe_tot_time) - InitElapsedStamp;
361     if (MutElapsedTime < 0) { MutElapsedTime = 0; }     /* sometimes -0.00 */
362
363     /* for SMP, we don't know the mutator time yet, we have to inspect
364      * all the running threads to find out, and they haven't stopped
365      * yet.  So we just timestamp MutUserTime at this point so we can
366      * calculate the EXIT time.  The real MutUserTime is calculated
367      * in stat_exit below.
368      */
369 #ifdef SMP
370     MutUserTime = CurrentUserTime;
371 #else
372     MutUserTime = CurrentUserTime - GC_tot_time - PROF_VAL(RP_tot_time + HC_tot_time) - InitUserTime;
373     if (MutUserTime < 0) { MutUserTime = 0; }
374 #endif
375 }
376
377 void
378 stat_endExit(void)
379 {
380     getTimes();
381 #ifdef SMP
382     ExitUserTime = CurrentUserTime - MutUserTime;
383 #else
384     ExitUserTime = CurrentUserTime - MutUserTime - GC_tot_time - PROF_VAL(RP_tot_time + HC_tot_time) - InitUserTime;
385 #endif
386     ExitElapsedTime = CurrentElapsedTime - MutElapsedStamp;
387     if (ExitUserTime < 0) {
388         ExitUserTime = 0;
389     }
390     if (ExitElapsedTime < 0) {
391         ExitElapsedTime = 0;
392     }
393 }
394
395 /* -----------------------------------------------------------------------------
396    Called at the beginning of each GC
397    -------------------------------------------------------------------------- */
398
399 static nat rub_bell = 0;
400
401 /*  initialise global variables needed during GC
402  *
403  *  * GC_start_time is read in mut_user_time_during_GC(), which in turn is 
404  *    needed if either PROFILING or DEBUGing is enabled
405  */
406 void
407 stat_startGC(void)
408 {
409     nat bell = RtsFlags.GcFlags.ringBell;
410
411     if (bell) {
412         if (bell > 1) {
413             debugBelch(" GC ");
414             rub_bell = 1;
415         } else {
416             debugBelch("\007");
417         }
418     }
419
420 #if defined(PROFILING) || defined(DEBUG)
421     getTimes();
422     GC_start_time = CurrentUserTime;  /* needed in mut_user_time_during_GC() */
423 #endif
424
425     if (RtsFlags.GcFlags.giveStats != NO_GC_STATS) {
426 #if !defined(PROFILING) && !defined(DEBUG)
427         getTimes();
428         GC_start_time = CurrentUserTime;
429 #endif
430         GCe_start_time = CurrentElapsedTime;
431         if (RtsFlags.GcFlags.giveStats) {
432             GC_start_faults = pageFaults();
433         }
434     }
435 }
436
437 /* -----------------------------------------------------------------------------
438    Called at the end of each GC
439    -------------------------------------------------------------------------- */
440
441 void
442 stat_endGC(lnat alloc, lnat collect, lnat live, lnat copied, lnat gen)
443 {
444     if (RtsFlags.GcFlags.giveStats != NO_GC_STATS) {
445         TICK_TYPE time, etime, gc_time, gc_etime;
446         
447         getTimes();
448         time     = CurrentUserTime;
449         etime    = CurrentElapsedTime;
450         gc_time  = time - GC_start_time;
451         gc_etime = etime - GCe_start_time;
452         
453         if (RtsFlags.GcFlags.giveStats == VERBOSE_GC_STATS) {
454             nat faults = pageFaults();
455             
456             statsPrintf("%9ld %9ld %9ld",
457                     alloc*sizeof(W_), collect*sizeof(W_), live*sizeof(W_));
458             statsPrintf(" %5.2f %5.2f %7.2f %7.2f %4ld %4ld  (Gen: %2ld)\n", 
459                     TICK_TO_DBL(gc_time),
460                     TICK_TO_DBL(gc_etime),
461                     TICK_TO_DBL(time),
462                     TICK_TO_DBL(etime - ElapsedTimeStart),
463                     faults - GC_start_faults,
464                     GC_start_faults - GC_end_faults,
465                     gen);
466
467             GC_end_faults = faults;
468             statsFlush();
469         }
470
471         GC_coll_times[gen] += gc_time;
472
473         GC_tot_copied += (ullong) copied;
474         GC_tot_alloc  += (ullong) alloc;
475         GC_tot_time   += gc_time;
476         GCe_tot_time  += gc_etime;
477         
478 #ifdef SMP
479         {
480             nat i;
481             pthread_t me = pthread_self();
482
483             for (i = 0; i < RtsFlags.ParFlags.nNodes; i++) {
484                 if (me == task_ids[i].id) {
485                     task_ids[i].gc_time += gc_time;
486                     task_ids[i].gc_etime += gc_etime;
487                     break;
488                 }
489             }
490         }
491 #endif
492
493         if (gen == RtsFlags.GcFlags.generations-1) { /* major GC? */
494             if (live > MaxResidency) {
495                 MaxResidency = live;
496             }
497             ResidencySamples++;
498             AvgResidency += live;
499         }
500     }
501
502     if (rub_bell) {
503         debugBelch("\b\b\b  \b\b\b");
504         rub_bell = 0;
505     }
506 }
507
508 /* -----------------------------------------------------------------------------
509    Called at the beginning of each Retainer Profiliing
510    -------------------------------------------------------------------------- */
511 #ifdef PROFILING
512 void
513 stat_startRP(void)
514 {
515   getTimes();
516   RP_start_time = CurrentUserTime;
517   RPe_start_time = CurrentElapsedTime;
518 }
519 #endif /* PROFILING */
520
521 /* -----------------------------------------------------------------------------
522    Called at the end of each Retainer Profiliing
523    -------------------------------------------------------------------------- */
524
525 #ifdef PROFILING
526 void
527 stat_endRP(
528   nat retainerGeneration,
529 #ifdef DEBUG_RETAINER
530   nat maxCStackSize,
531   int maxStackSize,
532 #endif
533   double averageNumVisit)
534 {
535   getTimes();
536   RP_tot_time += CurrentUserTime - RP_start_time;
537   RPe_tot_time += CurrentElapsedTime - RPe_start_time;
538
539   fprintf(prof_file, "Retainer Profiling: %d, at %f seconds\n", 
540     retainerGeneration, mut_user_time_during_RP());
541 #ifdef DEBUG_RETAINER
542   fprintf(prof_file, "\tMax C stack size = %u\n", maxCStackSize);
543   fprintf(prof_file, "\tMax auxiliary stack size = %u\n", maxStackSize);
544 #endif
545   fprintf(prof_file, "\tAverage number of visits per object = %f\n", averageNumVisit);
546 }
547 #endif /* PROFILING */
548
549 /* -----------------------------------------------------------------------------
550    Called at the beginning of each heap census
551    -------------------------------------------------------------------------- */
552 #ifdef PROFILING
553 void
554 stat_startHeapCensus(void)
555 {
556   getTimes();
557   HC_start_time = CurrentUserTime;
558   HCe_start_time = CurrentElapsedTime;
559 }
560 #endif /* PROFILING */
561
562 /* -----------------------------------------------------------------------------
563    Called at the end of each heap census
564    -------------------------------------------------------------------------- */
565 #ifdef PROFILING
566 void
567 stat_endHeapCensus(void) 
568 {
569   getTimes();
570   HC_tot_time += CurrentUserTime - HC_start_time;
571   HCe_tot_time += CurrentElapsedTime - HCe_start_time;
572 }
573 #endif /* PROFILING */
574
575 /* -----------------------------------------------------------------------------
576    stat_workerStop
577
578    Called under SMP when a worker thread finishes.  We drop the timing
579    stats for this thread into the task_ids struct for that thread.
580    -------------------------------------------------------------------------- */
581
582 #if defined(SMP)
583 void
584 stat_workerStop(void)
585 {
586     nat i;
587     pthread_t me = pthread_self();
588
589     getTimes();
590
591     for (i = 0; i < RtsFlags.ParFlags.nNodes; i++) {
592         if (task_ids[i].id == me) {
593             task_ids[i].mut_time = CurrentUserTime - task_ids[i].gc_time;
594             task_ids[i].mut_etime = CurrentElapsedTime
595                 - GCe_tot_time
596                 - task_ids[i].elapsedtimestart;
597             if (task_ids[i].mut_time < 0.0)  { task_ids[i].mut_time = 0.0;  }
598             if (task_ids[i].mut_etime < 0.0) { task_ids[i].mut_etime = 0.0; }
599         }
600     }
601 }
602 #endif
603
604 #if defined(SMP)
605 long int stat_getElapsedTime ()
606 {
607   getTimes();
608   return CurrentElapsedTime;
609 }
610 #endif
611
612 /* -----------------------------------------------------------------------------
613    Called at the end of execution
614
615    NOTE: number of allocations is not entirely accurate: it doesn't
616    take into account the few bytes at the end of the heap that
617    were left unused when the heap-check failed.
618    -------------------------------------------------------------------------- */
619
620 void
621 stat_exit(int alloc)
622 {
623     if (RtsFlags.GcFlags.giveStats != NO_GC_STATS) {
624
625         char temp[BIG_STRING_LEN];
626         TICK_TYPE time;
627         TICK_TYPE etime;
628         nat g, total_collections = 0;
629
630         getTimes();
631         time = CurrentUserTime;
632         etime = CurrentElapsedTime - ElapsedTimeStart;
633
634         GC_tot_alloc += alloc;
635
636         /* avoid divide by zero if time is measured as 0.00 seconds -- SDM */
637         if (time  == 0.0)  time = 1;
638         if (etime == 0.0) etime = 1;
639         
640         /* Count total garbage collections */
641         for (g = 0; g < RtsFlags.GcFlags.generations; g++)
642             total_collections += generations[g].collections;
643
644         /* For SMP, we have to get the user time from each thread
645          * and try to work out the total time.
646          */
647 #ifdef SMP
648         {   nat i;
649             MutUserTime = 0.0;
650             for (i = 0; i < RtsFlags.ParFlags.nNodes; i++) {
651                 MutUserTime += task_ids[i].mut_time;
652             }
653         }
654         time = MutUserTime + GC_tot_time + InitUserTime + ExitUserTime;
655         if (MutUserTime < 0) { MutUserTime = 0; }
656 #endif
657
658         if (RtsFlags.GcFlags.giveStats >= VERBOSE_GC_STATS) {
659             statsPrintf("%9ld %9.9s %9.9s", (lnat)alloc*sizeof(W_), "", "");
660             statsPrintf(" %5.2f %5.2f\n\n", 0.0, 0.0);
661         }
662
663         if (RtsFlags.GcFlags.giveStats >= SUMMARY_GC_STATS) {
664             ullong_format_string(GC_tot_alloc*sizeof(W_), 
665                                  temp, rtsTrue/*commas*/);
666             statsPrintf("%11s bytes allocated in the heap\n", temp);
667
668             ullong_format_string(GC_tot_copied*sizeof(W_), 
669                                  temp, rtsTrue/*commas*/);
670             statsPrintf("%11s bytes copied during GC\n", temp);
671
672             if ( ResidencySamples > 0 ) {
673                 ullong_format_string(MaxResidency*sizeof(W_), 
674                                      temp, rtsTrue/*commas*/);
675                 statsPrintf("%11s bytes maximum residency (%ld sample(s))\n",
676                         temp, ResidencySamples);
677             }
678             statsPrintf("\n");
679
680             /* Print garbage collections in each gen */
681             for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
682                 statsPrintf("%11d collections in generation %d (%6.2fs)\n", 
683                         generations[g].collections, g, 
684                         TICK_TO_DBL(GC_coll_times[g]));
685             }
686
687             statsPrintf("\n%11ld Mb total memory in use\n\n", 
688                     mblocks_allocated * MBLOCK_SIZE / (1024 * 1024));
689
690 #ifdef SMP
691             {
692                 nat i;
693                 for (i = 0; i < RtsFlags.ParFlags.nNodes; i++) {
694                     statsPrintf("  Task %2d:  MUT time: %6.2fs  (%6.2fs elapsed)\n"
695                             "            GC  time: %6.2fs  (%6.2fs elapsed)\n\n", 
696                             i, 
697                             TICK_TO_DBL(task_ids[i].mut_time),
698                             TICK_TO_DBL(task_ids[i].mut_etime),
699                             TICK_TO_DBL(task_ids[i].gc_time),
700                             TICK_TO_DBL(task_ids[i].gc_etime));
701                 }
702             }
703 #endif
704
705             statsPrintf("  INIT  time  %6.2fs  (%6.2fs elapsed)\n",
706                     TICK_TO_DBL(InitUserTime), TICK_TO_DBL(InitElapsedTime));
707             statsPrintf("  MUT   time  %6.2fs  (%6.2fs elapsed)\n",
708                     TICK_TO_DBL(MutUserTime), TICK_TO_DBL(MutElapsedTime));
709             statsPrintf("  GC    time  %6.2fs  (%6.2fs elapsed)\n",
710                     TICK_TO_DBL(GC_tot_time), TICK_TO_DBL(GCe_tot_time));
711 #ifdef PROFILING
712             statsPrintf("  RP    time  %6.2fs  (%6.2fs elapsed)\n",
713                     TICK_TO_DBL(RP_tot_time), TICK_TO_DBL(RPe_tot_time));
714             statsPrintf("  PROF  time  %6.2fs  (%6.2fs elapsed)\n",
715                     TICK_TO_DBL(HC_tot_time), TICK_TO_DBL(HCe_tot_time));
716 #endif 
717             statsPrintf("  EXIT  time  %6.2fs  (%6.2fs elapsed)\n",
718                     TICK_TO_DBL(ExitUserTime), TICK_TO_DBL(ExitElapsedTime));
719             statsPrintf("  Total time  %6.2fs  (%6.2fs elapsed)\n\n",
720                     TICK_TO_DBL(time), TICK_TO_DBL(etime));
721             statsPrintf("  %%GC time     %5.1f%%  (%.1f%% elapsed)\n\n",
722                     TICK_TO_DBL(GC_tot_time)*100/TICK_TO_DBL(time),
723                     TICK_TO_DBL(GCe_tot_time)*100/TICK_TO_DBL(etime));
724
725             if (time - GC_tot_time - PROF_VAL(RP_tot_time + HC_tot_time) == 0)
726                 ullong_format_string(0, temp, rtsTrue/*commas*/);
727             else
728                 ullong_format_string(
729                     (ullong)((GC_tot_alloc*sizeof(W_))/
730                              TICK_TO_DBL(time - GC_tot_time - 
731                                          PROF_VAL(RP_tot_time + HC_tot_time))),
732                     temp, rtsTrue/*commas*/);
733             
734             statsPrintf("  Alloc rate    %s bytes per MUT second\n\n", temp);
735         
736             statsPrintf("  Productivity %5.1f%% of total user, %.1f%% of total elapsed\n\n",
737                     TICK_TO_DBL(time - GC_tot_time - 
738                                 PROF_VAL(RP_tot_time + HC_tot_time) - InitUserTime) * 100 
739                     / TICK_TO_DBL(time), 
740                     TICK_TO_DBL(time - GC_tot_time - 
741                                 PROF_VAL(RP_tot_time + HC_tot_time) - InitUserTime) * 100 
742                     / TICK_TO_DBL(etime));
743         }
744
745         if (RtsFlags.GcFlags.giveStats == ONELINE_GC_STATS) {
746           /* print the long long separately to avoid bugginess on mingwin (2001-07-02, mingw-0.5) */
747           statsPrintf("<<ghc: %llu bytes, ", GC_tot_alloc*sizeof(W_));
748           statsPrintf("%d GCs, %ld/%ld avg/max bytes residency (%ld samples), %luM in use, %.2f INIT (%.2f elapsed), %.2f MUT (%.2f elapsed), %.2f GC (%.2f elapsed) :ghc>>\n",
749                     total_collections,
750                     ResidencySamples == 0 ? 0 : 
751                         AvgResidency*sizeof(W_)/ResidencySamples, 
752                     MaxResidency*sizeof(W_), 
753                     ResidencySamples,
754                     (unsigned long)(mblocks_allocated * MBLOCK_SIZE / (1024L * 1024L)),
755                     TICK_TO_DBL(InitUserTime), TICK_TO_DBL(InitElapsedTime),
756                     TICK_TO_DBL(MutUserTime), TICK_TO_DBL(MutElapsedTime),
757                     TICK_TO_DBL(GC_tot_time), TICK_TO_DBL(GCe_tot_time));
758         }
759
760         statsFlush();
761         statsClose();
762     }
763 }
764
765 /* -----------------------------------------------------------------------------
766    stat_describe_gens
767
768    Produce some detailed info on the state of the generational GC.
769    -------------------------------------------------------------------------- */
770 #ifdef DEBUG
771 void
772 statDescribeGens(void)
773 {
774   nat g, s, mut, mut_once, lge, live;
775   StgMutClosure *m;
776   bdescr *bd;
777   step *step;
778
779   debugBelch("     Gen    Steps      Max   Mutable  Mut-Once  Step   Blocks     Live    Large\n                    Blocks  Closures  Closures                          Objects\n");
780
781   for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
782     for (m = generations[g].mut_list, mut = 0; m != END_MUT_LIST; 
783          m = m->mut_link) 
784       mut++;
785     for (m = generations[g].mut_once_list, mut_once = 0; m != END_MUT_LIST; 
786          m = m->mut_link) 
787       mut_once++;
788     debugBelch("%8d %8d %8d %9d %9d", g, generations[g].n_steps,
789             generations[g].max_blocks, mut, mut_once);
790
791     for (s = 0; s < generations[g].n_steps; s++) {
792       step = &generations[g].steps[s];
793       for (bd = step->large_objects, lge = 0; bd; bd = bd->link)
794         lge++;
795       live = 0;
796       if (RtsFlags.GcFlags.generations == 1) {
797         bd = step->to_blocks;
798       } else {
799         bd = step->blocks;
800       }
801       for (; bd; bd = bd->link) {
802         live += (bd->free - bd->start) * sizeof(W_);
803       }
804       if (s != 0) {
805         debugBelch("%46s","");
806       }
807       debugBelch("%6d %8d %8d %8d\n", s, step->n_blocks,
808               live, lge);
809     }
810   }
811   debugBelch("\n");
812 }
813 #endif
814
815 /* -----------------------------------------------------------------------------
816    Stats available via a programmatic interface, so eg. GHCi can time
817    each compilation and expression evaluation.
818    -------------------------------------------------------------------------- */
819
820 extern HsInt64 getAllocations( void ) 
821 { return (HsInt64)total_allocated * sizeof(W_); }
822
823 /* -----------------------------------------------------------------------------
824    Dumping stuff in the stats file, or via the debug message interface
825    -------------------------------------------------------------------------- */
826
827 static void
828 statsPrintf( char *s, ... )
829 {
830     FILE *sf = RtsFlags.GcFlags.statsFile;
831     va_list ap;
832     
833     va_start(ap,s);
834     if (sf == NULL) {
835         vdebugBelch(s,ap);
836     } else {
837         vfprintf(sf, s, ap);
838     }
839     va_end(ap);
840 }
841
842 static void
843 statsFlush( void )
844 {
845     FILE *sf = RtsFlags.GcFlags.statsFile;
846     if (sf != NULL) {
847         fflush(sf);
848     }
849 }
850
851 static void
852 statsClose( void )
853 {
854     FILE *sf = RtsFlags.GcFlags.statsFile;
855     if (sf != NULL) {
856         fclose(sf);
857     }
858 }