]> git.notmuchmail.org Git - fips/blob - metrics.c
Fix uninitialized-value compile warning.
[fips] / metrics.c
1 /* Copyright © 2013, Intel Corporation
2  *
3  * Permission is hereby granted, free of charge, to any person obtaining a copy
4  * of this software and associated documentation files (the "Software"), to deal
5  * in the Software without restriction, including without limitation the rights
6  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7  * copies of the Software, and to permit persons to whom the Software is
8  * furnished to do so, subject to the following conditions:
9  *
10  * The above copyright notice and this permission notice shall be included in
11  * all copies or substantial portions of the Software.
12  *
13  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19  * THE SOFTWARE.
20  */
21
22 #define _GNU_SOURCE
23
24 #include <inttypes.h>
25
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <assert.h>
29 #include <time.h>
30 #include <sys/time.h>
31 #include <string.h>
32 #include <errno.h>
33
34 #include "fips-dispatch-gl.h"
35
36 #include "metrics.h"
37 #include "context.h"
38 #include "metrics-info.h"
39 #include "xmalloc.h"
40
41 int frames;
42 int verbose;
43
44 #define MAX_MONITORS_IN_FLIGHT 1000
45
46 /* Timer query */
47 typedef struct timer_query
48 {
49         unsigned id;
50
51         metrics_op_t op;
52         struct timer_query *next;
53 } timer_query_t;
54
55 /* Performance-monitor query */
56 typedef struct monitor
57 {
58         unsigned id;
59
60         metrics_op_t op;
61         struct monitor *next;
62 } monitor_t;
63
64 typedef struct op_metrics
65 {
66         /* This happens to also be the index into the
67          * metrics->op_metrics array currently
68          */
69         metrics_op_t op;
70         double time_ns;
71
72         double **counters;
73 } op_metrics_t;
74
75 struct metrics
76 {
77         /* Description of all available peformance counters, counter
78          * groups, their names and IDs, etc. */
79         metrics_info_t *info;
80
81         /* The current operation being measured. */
82         metrics_op_t op;
83
84         /* GL_TIME_ELAPSED query for which glEndQuery has not yet
85          * been called. */
86         unsigned timer_begun_id;
87
88         /* GL_TIME_ELAPSED queries for which glEndQuery has been
89          * called, (but results have not yet been queried). */
90         timer_query_t *timer_head;
91         timer_query_t *timer_tail;
92
93         /* Performance monitor for which glEndPerfMonitorAMD has not
94          * yet been called. */
95         unsigned monitor_begun_id;
96
97         /* Performance monitors for which glEndPerfMonitorAMD has
98          * been called, (but results have not yet been queried). */
99         monitor_t *monitor_head;
100         monitor_t *monitor_tail;
101
102         int monitors_in_flight;
103
104         unsigned num_op_metrics;
105         op_metrics_t *op_metrics;
106
107         /* Per-frame time and latency measurement. */
108         GLint64 swap_begin_timestamp;
109         unsigned swap_end_timestamp_id;
110         GLint64 previous_swap_end_timestamp;
111
112         struct timespec previous_cpu_time_ts;
113         struct timespec cpu_time_ts;
114 };
115
116 metrics_t *
117 metrics_create (metrics_info_t *info)
118 {
119         metrics_t *metrics;
120
121         metrics = xmalloc (sizeof (metrics_t));
122
123         metrics->info = info;
124
125         metrics->op = 0;
126
127         metrics->timer_begun_id = 0;
128
129         metrics->timer_head = NULL;
130         metrics->timer_tail = NULL;
131
132         metrics->monitor_begun_id = 0;
133
134         metrics->monitor_head = NULL;
135         metrics->monitor_tail = NULL;
136
137         metrics->monitors_in_flight = 0;
138
139         metrics->num_op_metrics = 0;
140         metrics->op_metrics = NULL;
141
142         glGenQueries (1, &metrics->swap_end_timestamp_id);
143
144         /* Get the first frame timestamp started immediately. */
145         glQueryCounter (metrics->swap_end_timestamp_id, GL_TIMESTAMP);
146
147         return metrics;
148 }
149
150 void
151 metrics_fini (metrics_t *metrics)
152 {
153         timer_query_t *timer, *timer_next;
154         monitor_t *monitor, *monitor_next;
155
156         /* Discard and cleanup any outstanding queries. */
157         if (metrics->timer_begun_id) {
158                 glEndQuery (GL_TIME_ELAPSED);
159                 glDeleteQueries (1, &metrics->timer_begun_id);
160                 metrics->timer_begun_id = 0;
161         }
162
163         for (timer = metrics->timer_head;
164              timer;
165              timer = timer_next)
166         {
167                 glDeleteQueries (1, &timer->id);
168                 timer_next = timer->next;
169                 free (timer);
170         }
171         metrics->timer_head = NULL;
172         metrics->timer_tail = NULL;
173
174         if (metrics->info->have_perfmon) {
175
176                 if (metrics->monitor_begun_id) {
177                         glEndPerfMonitorAMD (metrics->monitor_begun_id);
178                         glDeletePerfMonitorsAMD (1, &metrics->monitor_begun_id);
179                         metrics->monitor_begun_id = 0;
180                 }
181
182                 for (monitor = metrics->monitor_head;
183                      monitor;
184                      monitor = monitor_next)
185                 {
186                         glDeletePerfMonitorsAMD (1, &monitor->id);
187                         monitor_next = monitor->next;
188                         free (monitor);
189                 }
190                 metrics->monitor_head = NULL;
191                 metrics->monitor_tail = NULL;
192
193         }
194
195         metrics->monitors_in_flight = 0;
196 }
197
198 void
199 metrics_destroy (metrics_t *metrics)
200 {
201         metrics_fini (metrics);
202
203         free (metrics);
204 }
205
206 static const char *
207 metrics_op_string (metrics_op_t op)
208 {
209         if (op >= METRICS_OP_SHADER)
210                 return "Shader program";
211
212         switch (op)
213         {
214         case METRICS_OP_ACCUM:
215                 return "glAccum*(+)";
216         case METRICS_OP_BUFFER_DATA:
217                 return "glBufferData(+)";
218         case METRICS_OP_BUFFER_SUB_DATA:
219                 return "glCopyBufferSubData*";
220         case METRICS_OP_BITMAP:
221                 return "glBitmap*";
222         case METRICS_OP_BLIT_FRAMEBUFFER:
223                 return "glBlitFramebuffer*";
224         case METRICS_OP_CLEAR:
225                 return "glClear(+)";
226         case METRICS_OP_CLEAR_BUFFER_DATA:
227                 return "glCearBufferData(+)";
228         case METRICS_OP_CLEAR_TEX_IMAGE:
229                 return "glClearTexImage(+)";
230         case METRICS_OP_COPY_PIXELS:
231                 return "glCopyPixels";
232         case METRICS_OP_COPY_TEX_IMAGE:
233                 return "glCopyTexImage(+)";
234         case METRICS_OP_DRAW_PIXELS:
235                 return "glDrawPixels";
236         case METRICS_OP_GET_TEX_IMAGE:
237                 return "glGetTexImage(+)";
238         case METRICS_OP_READ_PIXELS:
239                 return "glReadPixels*";
240         case METRICS_OP_TEX_IMAGE:
241                 return "glTexImage*(+)";
242         default:
243                 fprintf (stderr, "fips: Internal error: "
244                          "Unknown metrics op value: %d\n", op);
245                 exit (1);
246         }
247
248         return "";
249 }
250
251 void
252 metrics_counter_start (metrics_t *metrics)
253 {
254         unsigned i;
255
256         /* Initialize the timer_query object. */
257         glGenQueries (1, &metrics->timer_begun_id);
258
259         /* Most everything else in this function is
260          * performance-monitor related. If we don't have that
261          * extension, just start the timer query and be done. */
262         if (! metrics->info->have_perfmon) {
263                 glBeginQuery (GL_TIME_ELAPSED, metrics->timer_begun_id);
264                 return;
265         }
266
267         /* Initialize the performance-monitor object */
268         glGenPerfMonitorsAMD (1, &metrics->monitor_begun_id);
269
270         for (i = 0; i < metrics->info->num_groups; i++)
271         {
272                 metrics_group_info_t *group;
273                 int num_counters;
274
275                 group = &metrics->info->groups[i];
276
277                 num_counters = group->num_counters;
278                 if (group->max_active_counters < group->num_counters)
279                 {
280                         fprintf (stderr, "Warning: Only monitoring %d/%d counters from group %d\n",
281                                  group->max_active_counters,
282                                  group->num_counters, i);
283                         num_counters = group->max_active_counters;
284
285                 }
286
287                 glSelectPerfMonitorCountersAMD(metrics->monitor_begun_id,
288                                                GL_TRUE, group->id,
289                                                num_counters,
290                                                group->counter_ids);
291         }
292
293         /* Start the queries */
294         glBeginQuery (GL_TIME_ELAPSED, metrics->timer_begun_id);
295
296         glBeginPerfMonitorAMD (metrics->monitor_begun_id);
297 }
298
299 void
300 metrics_counter_stop (metrics_t *metrics)
301 {
302         timer_query_t *timer;
303         monitor_t *monitor;
304
305         /* Stop the current timer and monitor. */
306         glEndQuery (GL_TIME_ELAPSED);
307
308         if (metrics->info->have_perfmon)
309                 glEndPerfMonitorAMD (metrics->monitor_begun_id);
310
311         /* Add these IDs to our lists of outstanding queries and
312          * monitors so the results can be collected later. */
313         timer = xmalloc (sizeof (timer_query_t));
314
315         timer->op = metrics->op;
316         timer->id = metrics->timer_begun_id;
317         timer->next = NULL;
318
319         if (metrics->timer_tail) {
320                 metrics->timer_tail->next = timer;
321                 metrics->timer_tail = timer;
322         } else {
323                 metrics->timer_tail = timer;
324                 metrics->timer_head = timer;
325         }
326
327         if (metrics->info->have_perfmon) {
328                 /* Create a new performance-monitor query */
329                 monitor = xmalloc (sizeof (monitor_t));
330
331                 monitor->op = metrics->op;
332                 monitor->id = metrics->monitor_begun_id;
333                 monitor->next = NULL;
334
335                 if (metrics->monitor_tail) {
336                         metrics->monitor_tail->next = monitor;
337                         metrics->monitor_tail = monitor;
338                 } else {
339                         metrics->monitor_tail = monitor;
340                         metrics->monitor_head = monitor;
341                 }
342         }
343
344         metrics->monitors_in_flight++;
345
346         /* Avoid being a resource hog and collect outstanding results
347          * once we have sent off a large number of
348          * queries. (Presumably, many of the outstanding queries are
349          * available by now.)
350          */
351         if (metrics->monitors_in_flight > MAX_MONITORS_IN_FLIGHT)
352                 metrics_collect_available (metrics);
353 }
354
355 void
356 metrics_set_current_op (metrics_t *metrics, metrics_op_t op)
357 {
358         metrics->op = op;
359 }
360
361 metrics_op_t
362 metrics_get_current_op (metrics_t *metrics)
363 {
364         return metrics->op;
365 }
366
367 static void
368 op_metrics_init (metrics_info_t *info, op_metrics_t *metrics, metrics_op_t op)
369 {
370         unsigned i, j;
371
372         metrics->op = op;
373         metrics->time_ns = 0.0;
374
375         metrics->counters = xmalloc (sizeof(double *) * info->num_groups);
376
377         for (i = 0; i < info->num_groups; i++) {
378                 metrics->counters[i] = xmalloc (sizeof (double) *
379                                                 info->groups[i].num_counters);
380                 for (j = 0; j < info->groups[i].num_counters; j++)
381                         metrics->counters[i][j] = 0.0;
382         }
383 }
384
385 static op_metrics_t *
386 _get_op_metrics (metrics_t *metrics, metrics_op_t op)
387 {
388         unsigned i;
389
390         if (op >= metrics->num_op_metrics)
391         {
392                 metrics->op_metrics = realloc (metrics->op_metrics,
393                                                (op + 1) * sizeof (op_metrics_t));
394                 for (i = metrics->num_op_metrics; i < op + 1; i++)
395                         op_metrics_init (metrics->info, &metrics->op_metrics[i], i);
396
397                 metrics->num_op_metrics = op + 1;
398         }
399
400         return &metrics->op_metrics[op];
401 }
402
403 static void
404 accumulate_program_metrics (metrics_t *metrics, metrics_op_t op,
405                             GLuint *result, GLuint size)
406 {
407 #define CONSUME(var)                                                    \
408         if (p + sizeof(var) > ((unsigned char *) result) + size)        \
409         {                                                               \
410                 fprintf (stderr, "Unexpected end-of-buffer while "      \
411                          "parsing results\n");                          \
412                 value = 0.0;                                            \
413                 break;                                                  \
414         }                                                               \
415         (var) = *((typeof(var) *) p);                                   \
416         p += sizeof(var);
417
418         metrics_info_t *info = metrics->info;
419         op_metrics_t *op_metrics = _get_op_metrics (metrics, op);
420         unsigned char *p = (unsigned char *) result;
421
422         while (p < ((unsigned char *) result) + size)
423         {
424                 GLuint group_id, group_index;
425                 GLuint counter_id, counter_index;
426                 metrics_group_info_t *group;
427                 double value;
428                 unsigned i;
429
430                 CONSUME (group_id);
431                 CONSUME (counter_id);
432
433                 for (i = 0; i < info->num_groups; i++) {
434                         if (info->groups[i].id == group_id)
435                                 break;
436                 }
437                 group_index = i;
438                 assert (group_index < info->num_groups);
439                 group = &info->groups[group_index];
440
441                 for (i = 0; i < group->num_counters; i++) {
442                         if (group->counter_ids[i] == counter_id)
443                                 break;
444                 }
445                 counter_index = i;
446                 assert (counter_index < group->num_counters);
447
448                 switch (group->counter_types[counter_index])
449                 {
450                         uint uint_value;
451                         uint64_t uint64_value;
452                         float float_value;
453                 case GL_UNSIGNED_INT:
454                         CONSUME (uint_value);
455                         value = uint_value;
456                         break;
457                 case GL_UNSIGNED_INT64_AMD:
458                         CONSUME (uint64_value);
459                         value = uint64_value;
460                         break;
461                 case GL_PERCENTAGE_AMD:
462                 case GL_FLOAT:
463                         CONSUME (float_value);
464                         value = float_value;
465                         break;
466                 default:
467                         fprintf (stderr, "fips: Warning: Unknown counter value type (%d)\n",
468                                  group->counter_types[counter_index]);
469                         value = 0.0;
470                         break;
471                 }
472
473                 op_metrics->counters[group_index][counter_index] += value;
474         }
475 }
476
477 static void
478 accumulate_program_time (metrics_t *metrics, metrics_op_t op, unsigned time_ns)
479 {
480         op_metrics_t *op_metrics;
481
482         op_metrics = _get_op_metrics (metrics, op);
483
484         op_metrics->time_ns += time_ns;
485 }
486
487 typedef struct per_stage_metrics
488 {
489         op_metrics_t *metrics;
490         shader_stage_info_t *stage;
491         double time_ns;
492         double active;
493 } per_stage_metrics_t;
494
495 static int
496 _is_shader_stage_counter (metrics_info_t *info,
497                           unsigned group_index,
498                           unsigned counter_index)
499 {
500         shader_stage_info_t *stage;
501         unsigned i;
502
503         for (i = 0; i < info->num_shader_stages; i++) {
504                 stage = &info->stages[i];
505
506                 if (stage->active_group_index == group_index &&
507                     stage->active_counter_index == counter_index)
508                 {
509                         return 1;
510                 }
511
512                 if (stage->stall_group_index == group_index &&
513                     stage->stall_counter_index == counter_index)
514                 {
515                         return 1;
516                 }
517         }
518
519         return 0;
520 }
521
522 static void
523 print_per_stage_metrics (metrics_t *metrics,
524                          per_stage_metrics_t *per_stage,
525                          double total)
526 {
527         metrics_info_t *info = metrics->info;
528         op_metrics_t *op_metrics = per_stage->metrics;
529         metrics_group_info_t *group;
530         const char *op_string;
531         unsigned group_index, counter;
532         double value;
533
534         /* Don't print anything for stages with no alloted time. */
535         if (per_stage->time_ns == 0.0)
536                 return;
537
538         op_string = metrics_op_string (op_metrics->op);
539
540         printf ("%21s", op_string);
541
542         if (op_metrics->op >= METRICS_OP_SHADER) {
543                 printf (" %3d", op_metrics->op - METRICS_OP_SHADER);
544         } else {
545                 printf ("    ");
546
547         }
548
549         if (per_stage->stage)
550                 printf (" %cS:", per_stage->stage->name[0]);
551         else
552                 printf ("   :");
553
554         printf ("\t%7.2f ms (%4.1f%%)",
555                 per_stage->time_ns / 1e6,
556                 per_stage->time_ns / total * 100);
557
558         if (per_stage->active)
559                 printf (", %4.1f%% active", per_stage->active * 100);
560
561         printf ("\n");
562
563         /* I'm not seeing a lot of value printing the rest of these
564          * performance counters by default yet. Use --verbose to get
565          * them for now. */
566         if (! verbose)
567                 return;
568
569         printf ("[");
570         for (group_index = 0; group_index < info->num_groups; group_index++) {
571                 group = &info->groups[group_index];
572                 for (counter = 0; counter < group->num_counters; counter++) {
573
574                         /* Don't print this counter value if it's a
575                          * per-stage cycle counter, (which we have
576                          * already accounted for). */
577                         if (_is_shader_stage_counter (info, group_index, counter))
578                                 continue;
579
580                         value = op_metrics->counters[group_index][counter];
581                         if (value == 0.0)
582                                 continue;
583                         printf ("%s: %.2f ", group->counter_names[counter],
584                                 value / 1e6);
585                 }
586         }
587         printf ("]\n");
588 }
589
590 static int
591 time_compare(const void *in_a, const void *in_b, void *arg unused)
592 {
593         const per_stage_metrics_t *a = in_a;
594         const per_stage_metrics_t *b = in_b;
595
596
597         if (a->time_ns < b->time_ns)
598                 return -1;
599         if (a->time_ns > b->time_ns)
600                 return 1;
601         return 0;
602 }
603
604 static void
605 print_program_metrics (metrics_t *metrics)
606 {
607         metrics_info_t *info = metrics->info;
608         unsigned num_shader_stages = info->num_shader_stages;
609         per_stage_metrics_t *sorted, *per_stage;
610         double total_time, op_cycles;
611         op_metrics_t *op;
612         unsigned group_index, counter_index;
613         unsigned i, j, num_sorted;
614
615         if (! info->have_perfmon &&
616             ! info->printed_missing_perfmon_warning)
617         {
618                 fprintf (stderr,
619                          "Warning: The GL_AMD_performance_monitor extensions is not available.\n"
620                          "         Some fips features, (such as per-shader-stage timings),\n"
621                          "         will not be available.\n");
622
623                 info->printed_missing_perfmon_warning = true;
624         }
625
626         /* Make a sorted list of the per-stage operations by time
627          * used, and figure out the total so we can print percentages.
628          */
629         if (num_shader_stages)
630                 num_sorted = metrics->num_op_metrics * num_shader_stages;
631         else
632                 num_sorted = metrics->num_op_metrics;
633
634         sorted = xmalloc (sizeof (*sorted) * num_sorted);
635
636         total_time = 0.0;
637
638         for (i = 0; i < metrics->num_op_metrics; i++) {
639
640                 op = &metrics->op_metrics[i];
641
642                 /* Accumulate total time across all ops. */
643                 total_time += op->time_ns;
644
645                 /* Also, find total cycles in all stages of this op. */
646                 op_cycles = 0.0;
647
648                 if (num_shader_stages == 0) {
649                         per_stage = &sorted[i];
650                         per_stage->metrics = op;
651                         per_stage->stage = NULL;
652                         per_stage->time_ns = op->time_ns;
653                         per_stage->active = 0.0;
654                 }
655
656                 for (j = 0; j < num_shader_stages; j++) {
657                         /* Active cycles */
658                         group_index = info->stages[j].active_group_index;
659                         counter_index = info->stages[j].active_counter_index;
660                         op_cycles += op->counters[group_index][counter_index];
661
662                         /* Stall cycles */
663                         group_index = info->stages[j].stall_group_index;
664                         counter_index = info->stages[j].stall_counter_index;
665                         op_cycles += op->counters[group_index][counter_index];
666                 }
667
668                 for (j = 0; j < num_shader_stages; j++) {
669                         double active_cycles, stall_cycles, stage_cycles;
670
671                         /* Active cycles */
672                         group_index = info->stages[j].active_group_index;
673                         counter_index = info->stages[j].active_counter_index;
674                         active_cycles = op->counters[group_index][counter_index];
675
676                         /* Stall cycles */
677                         group_index = info->stages[j].stall_group_index;
678                         counter_index = info->stages[j].stall_counter_index;
679                         stall_cycles = op->counters[group_index][counter_index];
680
681                         stage_cycles = active_cycles + stall_cycles;
682
683                         per_stage = &sorted[i * num_shader_stages + j];
684                         per_stage->metrics = op;
685
686                         if (op_cycles) {
687                                 per_stage->stage = &info->stages[j];
688                                 per_stage->time_ns = op->time_ns * (stage_cycles / op_cycles);
689                         } else {
690                                 /* If we don't have any per-stage cycle counts
691                                  * for this operation, then use the first
692                                  * stage as a placeholder for all the time,
693                                  * but NULL-ify the stage info so that the
694                                  * report doesn't lie about this time being
695                                  * from any particular stage. */
696                                 per_stage->stage = NULL;
697                                 if (j == 0) {
698                                         per_stage->time_ns = op->time_ns;
699                                 } else {
700                                         per_stage->time_ns = 0.0;
701                                 }
702                         }
703
704                         if (stage_cycles) {
705                                 per_stage->active = active_cycles / stage_cycles;
706                         } else {
707                                 per_stage->active = 0.0;
708                         }
709                 }
710         }
711
712         qsort_r (sorted, num_sorted, sizeof (*sorted),
713                  time_compare, metrics->op_metrics);
714
715         for (i = 0; i < num_sorted; i++)
716                 print_per_stage_metrics (metrics, &sorted[i], total_time);
717
718         free (sorted);
719 }
720
721 void
722 metrics_collect_available (metrics_t *metrics)
723 {
724         /* Consume all timer queries that are ready. */
725         timer_query_t *timer = metrics->timer_head;
726
727         while (timer) {
728                 GLuint available, elapsed;
729
730                 glGetQueryObjectuiv (timer->id,
731                                      GL_QUERY_RESULT_AVAILABLE, &available);
732                 if (! available)
733                         break;
734
735                 glGetQueryObjectuiv (timer->id,
736                                      GL_QUERY_RESULT, &elapsed);
737
738                 accumulate_program_time (metrics, timer->op, elapsed);
739
740                 metrics->timer_head = timer->next;
741                 if (metrics->timer_head == NULL)
742                         metrics->timer_tail = NULL;
743
744                 glDeleteQueries (1, &timer->id);
745
746                 free (timer);
747                 timer = metrics->timer_head;
748         }
749
750         if (! metrics->info->have_perfmon)
751                 return;
752
753         /* And similarly for all performance monitors that are ready. */
754         monitor_t *monitor = metrics->monitor_head;
755
756         while (monitor) {
757                 GLuint available, result_size, *result;
758                 GLint bytes_written;
759
760                 glGetPerfMonitorCounterDataAMD (monitor->id,
761                                                 GL_PERFMON_RESULT_AVAILABLE_AMD,
762                                                 sizeof (available), &available,
763                                                 NULL);
764                 if (! available)
765                         break;
766
767                 glGetPerfMonitorCounterDataAMD (monitor->id,
768                                                 GL_PERFMON_RESULT_SIZE_AMD,
769                                                 sizeof (result_size),
770                                                 &result_size, NULL);
771
772                 result = xmalloc (result_size);
773
774                 glGetPerfMonitorCounterDataAMD (monitor->id,
775                                                 GL_PERFMON_RESULT_AMD,
776                                                 result_size, result,
777                                                 &bytes_written);
778
779                 accumulate_program_metrics (metrics, monitor->op, result, result_size);
780
781                 free (result);
782
783                 metrics->monitor_head = monitor->next;
784                 if (metrics->monitor_head == NULL)
785                         metrics->monitor_tail = NULL;
786
787                 glDeletePerfMonitorsAMD (1, &monitor->id);
788
789                 free (monitor);
790
791                 metrics->monitors_in_flight--;
792
793                 monitor = metrics->monitor_head;
794         }
795 }
796
797 /* Return the difference from ts0 to ts1 as floating-point seconds. */
798 #define TIMESPEC_DIFF(ts0, ts1) (double) (ts1.tv_sec - ts0.tv_sec + \
799                                           (ts1.tv_nsec - ts0.tv_nsec) / 1e9)
800
801 void
802 metrics_end_frame_pre_swap (metrics_t *metrics)
803 {
804         GLuint64 swap_end_timestamp, frame_time_ns, latency_ns;
805         double cpu_time;
806
807         /* Don't leave any counters running over the end_frame work we
808          * do here. The counters will be started again at the end of
809          * metrics_end_frame_post_swap.  */
810
811         metrics_counter_stop (metrics);
812
813         /* Now that an entire frame's worth of content has gone by, we
814          * can be sure that the timer quiery for the previous frame's
815          * swap is available.
816          *
817          * Note: The only case in which this query isn't immediately
818          * available would be if there was effectively nothing in this
819          * frame. In that case, triggering a block on this query
820          * result is not a concern (since an empty frame is not
821          * interesting, and all of our counters are stopped anyway).
822          *
823          * Accepting this one block is much better than adding a
824          * linked list for these results that would reaslisticly never
825          * have more than one entry anyway.
826          */
827
828         glGetQueryObjectui64v (metrics->swap_end_timestamp_id,
829                                GL_QUERY_RESULT, &swap_end_timestamp);
830
831         if (frames == 0) {
832                 /* Print header */
833                 printf ("# frame: Frame_Number Frame_Time_milliseconds Frame_latency_milliseconds CPU_load GPU_load\n");
834         } else {
835                 /* Subtract previous frame's times to get frame times. */
836                 frame_time_ns = swap_end_timestamp - metrics->previous_swap_end_timestamp;
837
838                 latency_ns = swap_end_timestamp - metrics->swap_begin_timestamp;
839
840                 cpu_time = TIMESPEC_DIFF (metrics->previous_cpu_time_ts, metrics->cpu_time_ts);
841
842                 /* We've waited one frame to ensure we have a timestamp
843                  * result. So the time we've actually measured here is
844                  * for the previous frame. */
845                 printf ("frame: %d %g %g %g %g\n",
846                         frames - 1,
847                         (double) frame_time_ns / 1e6,
848                         (double) latency_ns / 1e6,
849                         cpu_time / (frame_time_ns / 1e9),
850                         0.0);
851         }
852
853         metrics->previous_swap_end_timestamp = swap_end_timestamp;
854         metrics->previous_cpu_time_ts = metrics->cpu_time_ts;
855
856         /* Before the actual swap call, we get the current timestamp
857          * value. This is a synchronous get so we can use this as the
858          * baseline for a frame latency measurment. */
859
860         glGetInteger64v (GL_TIMESTAMP, &metrics->swap_begin_timestamp);
861 }
862
863 void
864 metrics_end_frame_post_swap (metrics_t *metrics)
865 {
866         static int initialized = 0;
867         static struct timeval tv_start, tv_now;
868         int err;
869
870         /* Now that the swap command has been queued, we issue an
871          * asynchronous query of the timestamp value. Comparing this
872          * to the synchronous get we just sent in
873          * metrics_end_frame_pre_swap allows us to measure the
874          * per-frame swap latency. */
875
876         glQueryCounter (metrics->swap_end_timestamp_id, GL_TIMESTAMP);
877
878         /* Query the total amount of CPU time spent by this process. */
879         err = clock_gettime (CLOCK_PROCESS_CPUTIME_ID, &metrics->cpu_time_ts);
880         if (err == -1 ) {
881                 fprintf (stderr, "Failed to query CPU time with clock_gettime: %s\n",
882                          strerror (errno));
883                 exit (1);
884         }
885
886         if (! initialized) {
887                 gettimeofday (&tv_start, NULL);
888                 if (getenv ("FIPS_VERBOSE"))
889                         verbose = 1;
890                 initialized = 1;
891         }
892
893         metrics_collect_available (metrics);
894
895         frames++;
896
897         if (frames % 15 == 0) {
898                 double fps;
899
900                 gettimeofday (&tv_now, NULL);
901
902                 fps = (double) frames / (tv_now.tv_sec - tv_start.tv_sec +
903                                          (tv_now.tv_usec - tv_start.tv_usec) / 1.0e6);
904
905                 printf("FPS: %.3f\n", fps);
906
907                 print_program_metrics (metrics);
908         }
909
910         /* Start the counter up again now that we're done. */
911         metrics_counter_start (metrics);
912 }