]> mj.ucw.cz Git - libucw.git/blob - lib/profile.c
sign mismatch fixed
[libucw.git] / lib / profile.c
1 /*
2  *      Sherlock Library -- Poor Man's Profiler
3  *
4  *      (c) 2001 Martin Mares <mj@ucw.cz>
5  */
6
7 #include "lib/lib.h"
8 #include "lib/profile.h"
9
10 #include <stdio.h>
11
12 /* PROFILE_TOD */
13
14 #include <sys/time.h>
15
16 void
17 prof_tod_init(struct prof_tod *c)
18 {
19   c->sec = c->usec = 0;
20 }
21
22 void
23 prof_tod_switch(struct prof_tod *o, struct prof_tod *n)
24 {
25   struct timeval tv;
26   gettimeofday(&tv, NULL);
27   if (n)
28     {
29       n->start_sec = tv.tv_sec;
30       n->start_usec = tv.tv_usec;
31     }
32   if (o)
33     {
34       o->sec += tv.tv_sec - o->start_sec;
35       o->usec += tv.tv_usec - o->start_usec;
36       if (o->usec < 0)
37         {
38           o->usec += 1000000;
39           o->sec++;
40         }
41       else while (o->usec >= 1000000)
42         {
43           o->usec -= 1000000;
44           o->sec--;
45         }
46     }
47 }
48
49 int
50 prof_tod_format(char *buf, struct prof_tod *c)
51 {
52   return sprintf(buf, "%d.%06d", c->sec, c->usec);
53 }
54
55 /* PROFILE_TSC */
56
57 #ifdef CPU_I386
58
59 void
60 prof_tsc_init(struct prof_tsc *c)
61 {
62   c->ticks = 0;
63 }
64
65 int
66 prof_tsc_format(char *buf, struct prof_tsc *c)
67 {
68   return sprintf(buf, "%Ld", c->ticks);
69 }
70
71 #endif
72
73 /* PROFILE_KTSC */
74
75 #ifdef CONFIG_LINUX
76
77 #include <fcntl.h>
78 #include <unistd.h>
79 static int self_prof_fd = -1;
80
81 void
82 prof_ktsc_init(struct prof_ktsc *c)
83 {
84   if (self_prof_fd < 0)
85     {
86       self_prof_fd = open("/proc/self/profile", O_RDONLY, 0);
87       if (self_prof_fd < 0)
88         die("Unable to open /proc/self/profile: %m");
89     }
90   c->ticks_user = 0;
91   c->ticks_sys = 0;
92 }
93
94 void
95 prof_ktsc_switch(struct prof_ktsc *o, struct prof_ktsc *n)
96 {
97   u64 u, s;
98   byte buf[256];
99
100   int l = pread(self_prof_fd, buf, sizeof(buf)-1, 0);
101   ASSERT(l > 0 && l < (int)sizeof(buf)-1);
102   buf[l] = 0;
103   l = sscanf(buf, "%Ld%Ld", &u, &s);
104   ASSERT(l == 2);
105
106   if (n)
107     {
108       n->start_user = u;
109       n->start_sys = s;
110     }
111   if (o)
112     {
113       u -= o->start_user;
114       o->ticks_user += u;
115       s -= o->start_sys;
116       o->ticks_sys += s;
117     }
118 }
119
120 int
121 prof_ktsc_format(char *buf, struct prof_ktsc *c)
122 {
123   return sprintf(buf, "%Ld+%Ld", c->ticks_user, c->ticks_sys);
124 }
125
126 #endif