1 /* -----------------------------------------------------------------------------
3 * (c) The GHC Team, 1998-2004
5 * Statistics and timing-related functions.
7 * ---------------------------------------------------------------------------*/
9 /* Alas, no. This source is non-posix.
10 #include "PosixSource.h"
19 #include "ParTicky.h" /* ToDo: move into Rts.h */
20 #include "Profiling.h"
27 #ifndef mingw32_HOST_OS
28 # ifdef HAVE_SYS_TIMES_H
29 # include <sys/times.h>
33 #ifdef HAVE_SYS_TIME_H
43 #if ! irix_HOST_OS && ! defined(mingw32_HOST_OS)
44 # if defined(HAVE_SYS_RESOURCE_H)
45 # include <sys/resource.h>
49 #ifdef HAVE_SYS_TIMEB_H
50 #include <sys/timeb.h>
61 #if defined(PAR) || !(!defined(HAVE_GETRUSAGE) || irix_HOST_OS || defined(mingw32_HOST_OS) || defined(cygwin32_HOST_OS))
62 #include <sys/resource.h>
66 #define BIG_STRING_LEN 512
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
73 #define TICK_TYPE long int
74 #define TICK_TO_DBL(t) ((double)(t) / TicksPerSecond)
76 static int TicksPerSecond = 0;
78 static TICK_TYPE ElapsedTimeStart = 0;
79 static TICK_TYPE CurrentElapsedTime = 0;
80 static TICK_TYPE CurrentUserTime = 0;
82 static TICK_TYPE InitUserTime = 0;
83 static TICK_TYPE InitElapsedTime = 0;
84 static TICK_TYPE InitElapsedStamp = 0;
86 static TICK_TYPE MutUserTime = 0;
87 static TICK_TYPE MutElapsedTime = 0;
88 static TICK_TYPE MutElapsedStamp = 0;
90 static TICK_TYPE ExitUserTime = 0;
91 static TICK_TYPE ExitElapsedTime = 0;
93 static ullong GC_tot_alloc = 0;
94 static ullong GC_tot_copied = 0;
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 */
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 */
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
108 #define PROF_VAL(x) (x)
110 #define PROF_VAL(x) 0
113 static lnat MaxResidency = 0; // in words; for stats only
114 static lnat AvgResidency = 0;
115 static lnat ResidencySamples = 0; // for stats only
117 static lnat GC_start_faults = 0, GC_end_faults = 0;
119 static TICK_TYPE *GC_coll_times;
121 static void getTimes(void);
122 static nat pageFaults(void);
124 static void statsPrintf( char *s, ... );
125 static void statsFlush( void );
126 static void statsClose( void );
128 /* elapsedtime() -- The current elapsed time in seconds */
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; \
136 (ll) |= (ft).dwLowDateTime; \
137 (ll) /= (unsigned long long) (HNS_PER_SEC / CLOCKS_PER_SEC)
140 #if defined(mingw32_HOST_OS) || defined(cygwin32_HOST_OS)
141 /* cygwin32 or mingw32 version */
145 static int is_win9x = -1;
147 FILETIME creationTime, exitTime, userTime, kernelTime = {0,0};
148 long long int kT, uT;
151 /* figure out whether we're on a Win9x box or not. */
155 /* Need to init the size field first.*/
156 oi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
157 b = GetVersionEx(&oi);
159 is_win9x = ( (b && (oi.dwPlatformId & VER_PLATFORM_WIN32_WINDOWS)) ? 1 : 0);
163 /* On Win9x, just attribute all running time to the user. */
167 SystemTimeToFileTime(&st,&userTime);
169 /* ToDo: pin down elapsed times to just the OS thread(s) that
170 are evaluating/managing Haskell code.
172 if (!GetProcessTimes (GetCurrentProcess(), &creationTime,
173 &exitTime, &kernelTime, &userTime)) {
174 /* Probably on a Win95 box..*/
175 CurrentElapsedTime = 0;
181 FT2longlong(kT,kernelTime);
182 FT2longlong(uT,userTime);
183 CurrentElapsedTime = uT + kT;
184 CurrentUserTime = uT;
187 /* Adjust for the fact that we're using system time & not
188 process time on Win9x. */
189 CurrentUserTime -= ElapsedTimeStart;
190 CurrentElapsedTime -= ElapsedTimeStart;
201 /* We will #ifdef around the fprintf for machines
202 we *know* are unsupported. (WDP 94/05)
204 debugBelch("NOTE: `getTimes' does nothing!\n");
207 #else /* not stumped */
209 clock_t r = times(&t);
211 CurrentElapsedTime = r;
212 CurrentUserTime = t.tms_utime;
218 /* mut_user_time_during_GC() and mut_user_time()
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
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)
231 mut_user_time_during_GC( void )
233 return TICK_TO_DBL(GC_start_time - GC_tot_time - PROF_VAL(RP_tot_time + HC_tot_time));
237 mut_user_time( void )
240 return TICK_TO_DBL(CurrentUserTime - GC_tot_time - PROF_VAL(RP_tot_time + HC_tot_time));
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();
250 mut_user_time_during_RP( void )
252 return TICK_TO_DBL(RP_start_time - GC_tot_time - RP_tot_time - HC_tot_time);
256 mut_user_time_during_heap_census( void )
258 return TICK_TO_DBL(HC_start_time - GC_tot_time - RP_tot_time - HC_tot_time);
260 #endif /* PROFILING */
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)
272 getrusage(RUSAGE_SELF, &t);
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");
287 (TICK_TYPE *)stgMallocBytes(
288 sizeof(TICK_TYPE)*RtsFlags.GcFlags.generations,
290 for (i = 0; i < RtsFlags.GcFlags.generations; i++) {
291 GC_coll_times[i] = 0;
295 /* -----------------------------------------------------------------------------
296 Initialisation time...
297 -------------------------------------------------------------------------- */
302 /* Determine TicksPerSecond ... */
303 #if defined(CLK_TCK) /* defined by POSIX */
304 TicksPerSecond = CLK_TCK;
306 #elif defined(HAVE_SYSCONF)
309 ticks = sysconf(_SC_CLK_TCK);
311 debugBelch("stat_init: bad call to 'sysconf'!\n");
312 stg_exit(EXIT_FAILURE);
314 TicksPerSecond = ticks;
316 /* no "sysconf" or CLK_TCK; had better guess */
320 #elif defined(CLOCKS_PER_SEC)
321 TicksPerSecond = CLOCKS_PER_SEC;
323 #else /* had better guess wildly */
324 /* We will #ifdef around the fprintf for machines
325 we *know* are unsupported. (WDP 94/05)
327 debugBelch("NOTE: Guessing `TicksPerSecond = 60'!\n");
332 ElapsedTimeStart = CurrentElapsedTime;
339 InitUserTime = CurrentUserTime;
340 InitElapsedStamp = CurrentElapsedTime;
341 if (ElapsedTimeStart > CurrentElapsedTime) {
344 InitElapsedTime = CurrentElapsedTime - ElapsedTimeStart;
348 /* -----------------------------------------------------------------------------
349 stat_startExit and stat_endExit
351 These two measure the time taken in shutdownHaskell().
352 -------------------------------------------------------------------------- */
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 */
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.
370 MutUserTime = CurrentUserTime;
372 MutUserTime = CurrentUserTime - GC_tot_time - PROF_VAL(RP_tot_time + HC_tot_time) - InitUserTime;
373 if (MutUserTime < 0) { MutUserTime = 0; }
382 ExitUserTime = CurrentUserTime - MutUserTime;
384 ExitUserTime = CurrentUserTime - MutUserTime - GC_tot_time - PROF_VAL(RP_tot_time + HC_tot_time) - InitUserTime;
386 ExitElapsedTime = CurrentElapsedTime - MutElapsedStamp;
387 if (ExitUserTime < 0) {
390 if (ExitElapsedTime < 0) {
395 /* -----------------------------------------------------------------------------
396 Called at the beginning of each GC
397 -------------------------------------------------------------------------- */
399 static nat rub_bell = 0;
401 /* initialise global variables needed during GC
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
409 nat bell = RtsFlags.GcFlags.ringBell;
420 #if defined(PROFILING) || defined(DEBUG)
422 GC_start_time = CurrentUserTime; /* needed in mut_user_time_during_GC() */
425 if (RtsFlags.GcFlags.giveStats != NO_GC_STATS) {
426 #if !defined(PROFILING) && !defined(DEBUG)
428 GC_start_time = CurrentUserTime;
430 GCe_start_time = CurrentElapsedTime;
431 if (RtsFlags.GcFlags.giveStats) {
432 GC_start_faults = pageFaults();
437 /* -----------------------------------------------------------------------------
438 Called at the end of each GC
439 -------------------------------------------------------------------------- */
442 stat_endGC(lnat alloc, lnat collect, lnat live, lnat copied, lnat gen)
444 if (RtsFlags.GcFlags.giveStats != NO_GC_STATS) {
445 TICK_TYPE time, etime, gc_time, gc_etime;
448 time = CurrentUserTime;
449 etime = CurrentElapsedTime;
450 gc_time = time - GC_start_time;
451 gc_etime = etime - GCe_start_time;
453 if (RtsFlags.GcFlags.giveStats == VERBOSE_GC_STATS) {
454 nat faults = pageFaults();
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),
462 TICK_TO_DBL(etime - ElapsedTimeStart),
463 faults - GC_start_faults,
464 GC_start_faults - GC_end_faults,
467 GC_end_faults = faults;
471 GC_coll_times[gen] += gc_time;
473 GC_tot_copied += (ullong) copied;
474 GC_tot_alloc += (ullong) alloc;
475 GC_tot_time += gc_time;
476 GCe_tot_time += gc_etime;
481 pthread_t me = pthread_self();
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;
493 if (gen == RtsFlags.GcFlags.generations-1) { /* major GC? */
494 if (live > MaxResidency) {
498 AvgResidency += live;
503 debugBelch("\b\b\b \b\b\b");
508 /* -----------------------------------------------------------------------------
509 Called at the beginning of each Retainer Profiliing
510 -------------------------------------------------------------------------- */
516 RP_start_time = CurrentUserTime;
517 RPe_start_time = CurrentElapsedTime;
519 #endif /* PROFILING */
521 /* -----------------------------------------------------------------------------
522 Called at the end of each Retainer Profiliing
523 -------------------------------------------------------------------------- */
528 nat retainerGeneration,
529 #ifdef DEBUG_RETAINER
533 double averageNumVisit)
536 RP_tot_time += CurrentUserTime - RP_start_time;
537 RPe_tot_time += CurrentElapsedTime - RPe_start_time;
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);
545 fprintf(prof_file, "\tAverage number of visits per object = %f\n", averageNumVisit);
547 #endif /* PROFILING */
549 /* -----------------------------------------------------------------------------
550 Called at the beginning of each heap census
551 -------------------------------------------------------------------------- */
554 stat_startHeapCensus(void)
557 HC_start_time = CurrentUserTime;
558 HCe_start_time = CurrentElapsedTime;
560 #endif /* PROFILING */
562 /* -----------------------------------------------------------------------------
563 Called at the end of each heap census
564 -------------------------------------------------------------------------- */
567 stat_endHeapCensus(void)
570 HC_tot_time += CurrentUserTime - HC_start_time;
571 HCe_tot_time += CurrentElapsedTime - HCe_start_time;
573 #endif /* PROFILING */
575 /* -----------------------------------------------------------------------------
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 -------------------------------------------------------------------------- */
584 stat_workerStop(void)
587 pthread_t me = pthread_self();
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
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; }
605 long int stat_getElapsedTime ()
608 return CurrentElapsedTime;
612 /* -----------------------------------------------------------------------------
613 Called at the end of execution
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 -------------------------------------------------------------------------- */
623 if (RtsFlags.GcFlags.giveStats != NO_GC_STATS) {
625 char temp[BIG_STRING_LEN];
628 nat g, total_collections = 0;
631 time = CurrentUserTime;
632 etime = CurrentElapsedTime - ElapsedTimeStart;
634 GC_tot_alloc += alloc;
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;
640 /* Count total garbage collections */
641 for (g = 0; g < RtsFlags.GcFlags.generations; g++)
642 total_collections += generations[g].collections;
644 /* For SMP, we have to get the user time from each thread
645 * and try to work out the total time.
650 for (i = 0; i < RtsFlags.ParFlags.nNodes; i++) {
651 MutUserTime += task_ids[i].mut_time;
654 time = MutUserTime + GC_tot_time + InitUserTime + ExitUserTime;
655 if (MutUserTime < 0) { MutUserTime = 0; }
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);
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);
668 ullong_format_string(GC_tot_copied*sizeof(W_),
669 temp, rtsTrue/*commas*/);
670 statsPrintf("%11s bytes copied during GC\n", temp);
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);
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]));
687 statsPrintf("\n%11ld Mb total memory in use\n\n",
688 mblocks_allocated * MBLOCK_SIZE / (1024 * 1024));
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",
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));
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));
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));
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));
725 if (time - GC_tot_time - PROF_VAL(RP_tot_time + HC_tot_time) == 0)
726 ullong_format_string(0, temp, rtsTrue/*commas*/);
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*/);
734 statsPrintf(" Alloc rate %s bytes per MUT second\n\n", temp);
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
740 TICK_TO_DBL(time - GC_tot_time -
741 PROF_VAL(RP_tot_time + HC_tot_time) - InitUserTime) * 100
742 / TICK_TO_DBL(etime));
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",
750 ResidencySamples == 0 ? 0 :
751 AvgResidency*sizeof(W_)/ResidencySamples,
752 MaxResidency*sizeof(W_),
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));
765 /* -----------------------------------------------------------------------------
768 Produce some detailed info on the state of the generational GC.
769 -------------------------------------------------------------------------- */
772 statDescribeGens(void)
774 nat g, s, mut, lge, live;
778 debugBelch(" Gen Steps Max Mutable Step Blocks Live Large\n Blocks Closures Closures Objects\n");
781 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
782 for (bd = generations[g].mut_list; bd != NULL; bd = bd->link) {
783 mut += bd->free - bd->start;
786 debugBelch("%8d %8d %8d %9d", g, generations[g].n_steps,
787 generations[g].max_blocks, mut);
789 for (s = 0; s < generations[g].n_steps; s++) {
790 step = &generations[g].steps[s];
791 for (bd = step->large_objects, lge = 0; bd; bd = bd->link)
794 if (RtsFlags.GcFlags.generations == 1) {
795 bd = step->to_blocks;
799 for (; bd; bd = bd->link) {
800 live += (bd->free - bd->start) * sizeof(W_);
803 debugBelch("%46s","");
805 debugBelch("%6d %8d %8d %8d\n", s, step->n_blocks,
813 /* -----------------------------------------------------------------------------
814 Stats available via a programmatic interface, so eg. GHCi can time
815 each compilation and expression evaluation.
816 -------------------------------------------------------------------------- */
818 extern HsInt64 getAllocations( void )
819 { return (HsInt64)total_allocated * sizeof(W_); }
821 /* -----------------------------------------------------------------------------
822 Dumping stuff in the stats file, or via the debug message interface
823 -------------------------------------------------------------------------- */
826 statsPrintf( char *s, ... )
828 FILE *sf = RtsFlags.GcFlags.statsFile;
843 FILE *sf = RtsFlags.GcFlags.statsFile;
852 FILE *sf = RtsFlags.GcFlags.statsFile;