BDE 4.14.0 Production release
Loading...
Searching...
No Matches
balb_performancemonitor.h
Go to the documentation of this file.
1/// @file balb_performancemonitor.h
2///
3/// The content of this file has been pre-processed for Doxygen.
4///
5
6
7// balb_performancemonitor.h -*-C++-*-
8#ifndef INCLUDED_BALB_PERFORMANCEMONITOR
9#define INCLUDED_BALB_PERFORMANCEMONITOR
10
11#include <bsls_ident.h>
12BSLS_IDENT("$Id: $")
13
14/// @defgroup balb_performancemonitor balb_performancemonitor
15/// @brief Provide a mechanism to collect process performance measures.
16/// @addtogroup bal
17/// @{
18/// @addtogroup balb
19/// @{
20/// @addtogroup balb_performancemonitor
21/// @{
22///
23/// <h1> Outline </h1>
24/// * <a href="#balb_performancemonitor-purpose"> Purpose</a>
25/// * <a href="#balb_performancemonitor-classes"> Classes </a>
26/// * <a href="#balb_performancemonitor-description"> Description </a>
27/// * <a href="#balb_performancemonitor-os-specific-permissions"> OS-Specific Permissions </a>
28/// * <a href="#balb_performancemonitor-unsupported-platformcompiler-mode---solarisg-32-bits"> Unsupported PlatformCompiler mode - Solarisg++32-bits </a>
29/// * <a href="#balb_performancemonitor-iterator-invalidation"> Iterator Invalidation </a>
30/// * <a href="#balb_performancemonitor-thread-safety"> Thread Safety </a>
31/// * <a href="#balb_performancemonitor-usage"> Usage </a>
32/// * <a href="#balb_performancemonitor-example-1-basic-use-of-balb-performancemonitor"> Example 1: Basic Use of balb::PerformanceMonitor </a>
33///
34/// # Purpose {#balb_performancemonitor-purpose}
35/// Provide a mechanism to collect process performance measures.
36///
37/// # Classes {#balb_performancemonitor-classes}
38///
39/// - balb::PerformanceMonitor: monitor process performance
40/// - balb::PerformanceMonitor::Statistics: performance stats
41/// - balb::PerformanceMonitor::ConstIterator: stats iteration
42///
43/// # Description {#balb_performancemonitor-description}
44/// This component provides an application developer the means to
45/// collect and report performance statistics for an arbitrary number of
46/// processes running on the local machine. The `balb::PerformanceMonitor`
47/// provides the mechanism for doing so, the
48/// `balb::PerformanceMonitor::Statistics` class holds the data and the
49/// `balb::PerformanceMonitor::ConstIterator` class is used to iterate over the
50/// data. The following table describes the measures collecting by this
51/// component. Note that all the collected measures are specific to the
52/// monitored process and do not refer to any system-wide measurement.
53/// @code
54/// Measure Identifier Description
55/// ------- ---------- -----------
56/// User CPU Time e_CPU_TIME_USER Total amount of time spent executing
57/// instructions in user mode.
58///
59/// System CPU Time e_CPU_TIME_SYSTEM Total amount of time spent executing
60/// instructions in kernel mode.
61///
62/// CPU Time e_CPU_TIME The sum of User and System CPU times.
63///
64/// User CPU % e_CPU_UTIL_USER Percentage of elapsed CPU time this
65/// process spent executing instructions
66/// in user mode.
67///
68/// System CPU % e_CPU_UTIL_SYSTEM Percentage of elapsed CPU time this
69/// process spent executing instructions
70/// in kernel mode.
71///
72/// CPU % e_CPU_UTIL Sum of User CPU % and System CPU %.
73///
74/// Resident Size e_RESIDENT_SIZE Number of mega-bytes of physical
75/// memory used by the process.
76///
77/// Virtual Size e_VIRTUAL_SIZE The size of the heap, in
78/// mega-bytes. This value does not
79/// include the size of the address
80/// space mapped to files (anonymous or
81/// otherwise.)
82///
83/// Thread Count e_NUM_THREADS Number of threads executing in the
84/// process.
85///
86/// Page Faults e_NUM_PAGEFAULTS Total number of page faults incurred
87/// throughout the lifetime of the
88/// process.
89/// @endcode
90///
91/// ## OS-Specific Permissions {#balb_performancemonitor-os-specific-permissions}
92///
93///
94/// Various OSs might require specific permissions in order to inspect processes
95/// other than the current process. For example, on Darwin, users other than
96/// root can only inspect processes running under the user with which the
97/// current process is running. This error condition will be indicated by a
98/// non-zero return value from `registerPid`.
99///
100/// ## Unsupported PlatformCompiler mode - Solarisg++32-bits {#balb_performancemonitor-unsupported-platformcompiler-mode---solarisg-32-bits}
101///
102///
103/// Note that this component is not supported when building in 32-bit mode
104/// with the g++ compiler on Solaris, due to Solaris's `procfs.h` header not
105/// supporting that compiler in 32-bit mode. (DRQS 170291732)
106///
107/// ## Iterator Invalidation {#balb_performancemonitor-iterator-invalidation}
108///
109///
110/// Registration of new pids does not invalidate existing iterators.
111/// Unregistration of a pid invalidates only iterators pointing to the
112/// statistics for the pid being unregistered. Additionally, unregistering a
113/// pid with a `balb::PerformanceMonitor` object invalidates all references to
114/// `Statistics` objects retrieved from those iterators. All other iterators
115/// remain valid.
116///
117/// ## Thread Safety {#balb_performancemonitor-thread-safety}
118///
119///
120/// The classes `balb::PerformanceMonitor` and
121/// `balb::PerformanceMonitor::Statistics`, provided by this component, are
122/// both independently fully *thread-safe* (see @ref bsldoc_glossary ). However,
123/// `balb::PerformanceMonitor::ConstIterator` is only *const* *thread-safe*,
124/// meaning it is not safe to access or modify a `ConstIterator` in one thread
125/// while another thread modifies the same object. As unregistering a pid with
126/// a `balb::PerformanceMonitor` object invalidates iterators (see {Iterator
127/// Invalidation}), external synchronization is needed if `unregisterPid` is
128/// called concurrently to iterating over statistics. Also, in a multi-threaded
129/// context, a `Statistics` object accessed via a reference (or pointer) from
130/// a `ConstIterator` object may have its statistics updated at any time by a
131/// call to `collect` or `resetStatistics` in another thread. If consistent
132/// access is needed to multiple items in a set of statistics, then the user
133/// should copy the statistics object, and then inspect the copy at their
134/// leisure.
135///
136/// Notice that this component was implemented with particular usage patterns in
137/// mind, which are captured in the usage examples.
138///
139/// ## Usage {#balb_performancemonitor-usage}
140///
141///
142/// This section illustrates intended use of this component.
143///
144/// ### Example 1: Basic Use of balb::PerformanceMonitor {#balb_performancemonitor-example-1-basic-use-of-balb-performancemonitor}
145///
146///
147/// The following example shows how to monitor the currently executing process
148/// and produce a formatted report of the collected measures after a certain
149/// interval.
150///
151/// First, we instantiate a scheduler used by the performance monitor to
152/// schedule collection events.
153/// @code
154/// bdlmt::TimerEventScheduler scheduler;
155/// scheduler.start();
156/// @endcode
157/// Then, we create the performance monitor, monitoring the current process and
158/// auto-collecting statistics every second.
159/// @code
160/// balb::PerformanceMonitor perfmon(&scheduler, 1.0);
161/// int rc = perfmon.registerPid(0, "perfmon");
162/// const int pid = bdls::ProcessUtil::getProcessId();
163///
164/// assert(0 == rc);
165/// assert(1 == perfmon.numRegisteredPids());
166/// @endcode
167/// Next, we print a formatted report of the performance statistics collected
168/// for each pid every 5 seconds for half a minute. Note, that `Statistics`
169/// object can be simultaneously modified by scheduler callback and accessed via
170/// a `ConstIterator`. To ensure that the call to `Statistics::print` outputs
171/// consistent data from a single update of the statistics for this process, we
172/// create a local copy (copy construction is guaranteed to be thread-safe).
173/// @code
174/// for (int i = 0; i < 6; ++i) {
175/// bslmt::ThreadUtil::microSleep(0, 5);
176///
177/// balb::PerformanceMonitor::ConstIterator it = perfmon.begin();
178/// const balb::PerformanceMonitor::Statistics stats = *it;
179///
180/// assert(pid == stats.pid());
181///
182/// bsl::cout << "PID = " << stats.pid() << ":\n";
183/// stats.print(bsl::cout);
184/// }
185/// @endcode
186/// Finally, we unregister the process and stop the scheduler to cease
187/// collecting statistics for this process. It is safe to call `unregisterPid`
188/// here, because we don't have any `ConstIterators` objects or references to
189/// `Statistics` objects.
190/// @code
191/// rc = perfmon.unregisterPid(pid);
192///
193/// assert(0 == rc);
194/// assert(0 == perfmon.numRegisteredPids());
195///
196/// scheduler.stop();
197/// @endcode
198/// @}
199/** @} */
200/** @} */
201
202/** @addtogroup bal
203 * @{
204 */
205/** @addtogroup balb
206 * @{
207 */
208/** @addtogroup balb_performancemonitor
209 * @{
210 */
211
212#include <balscm_version.h>
213
214#include <bslmt_readlockguard.h>
215#include <bslmt_rwmutex.h>
216
218
219#include <bsls_atomic.h>
220
221#include <bdlt_datetime.h>
222
223#include <bsls_timeinterval.h>
224
225#include <bslma_allocator.h>
227
229
230#include <bsls_assert.h>
231#include <bsls_platform.h>
232#include <bsls_types.h>
233
234#include <bsl_iosfwd.h>
235#include <bsl_iterator.h>
236#include <bsl_map.h>
237#include <bsl_memory.h>
238#include <bsl_string.h>
239
240
241namespace balb {
242
243 // ========================
244 // class PerformanceMonitor
245 // ========================
246
247/// Provides a mechanism to collect performance statistics for an arbitrary
248/// number of processes running on the local machine.
249///
250/// See @ref balb_performancemonitor
252
253 public:
254 // FRIENDS
255 class Statistics;
256 friend class Statistics;
257 // Grant visibility of private types to 'Statistics'.
258
259 class ConstIterator;
260 friend class ConstIterator;
261 // Grant visibility of private types to 'ConstIterator'.
262
263 private:
264 // PRIVATE TYPES
265
266 // Defines a type alias for the operating system type discovered by the
267 // 'bsls::platform' component. This type alias is used to specifically
268 // select a particular template specialization of the 'Collector' template.
269
270#if defined(BSLS_PLATFORM_OS_LINUX) || defined(BSLS_PLATFORM_OS_CYGWIN)
271 typedef bsls::Platform::OsLinux OsType;
272#elif defined(BSLS_PLATFORM_OS_FREEBSD)
273 typedef bsls::Platform::OsFreeBsd OsType;
274#elif defined(BSLS_PLATFORM_OS_DARWIN)
275 typedef bsls::Platform::OsDarwin OsType;
276#elif defined(BSLS_PLATFORM_OS_UNIX)
277 typedef bsls::Platform::OsUnix OsType;
278#elif defined(BSLS_PLATFORM_OS_WINDOWS)
279 typedef bsls::Platform::OsWindows OsType;
280#endif
281
282 /// Forward declares a class template for a performance measure
283 /// collector for a parameterized `PLATFORM`. This class template is
284 /// never defined. Instead, we define explicit specializations for
285 /// supported platforms. Any attempt to compile this component on
286 /// unsupported platforms will result in a compile-time error.
287 template <class PLATFORM>
288 class Collector;
289
290 /// Defines a type alias for the type that defines the private platform-
291 /// specific mechanism used to collect the performance measures for a
292 /// pid.
293 typedef Collector<OsType> CollectorType;
294
295 /// Defines a type alias for the shared pointer to the platform-specific
296 /// mechanism used to collect the performance measures for a pid.
298
299 /// Defines a type alias for the shared pointer to the platform-specific
300 /// mechanism used to collect the performance measures for a pid.
302
303 /// Defines a type alias for the map of pids to their collected
304 /// statistics and associated platform-specific collector
305 /// implementation.
307
308 // DATA
309 PidMap d_pidMap; // map of pid stats
310
311 double d_interval; // collection interval
312
313 bdlmt::TimerEventScheduler *d_scheduler_p; // scheduler of
314 // collection events
315 // (held)
316
317 bdlmt::TimerEventScheduler::Handle d_clock; // handle to collection
318 // timer
319
320 mutable bslmt::RWMutex d_mapGuard; // serializes write
321 // access to 'd_pidMap'
322
323 bslma::Allocator *d_allocator_p; // supplies memory
324 // (held)
325
326 private:
327 // NOT IMPLEMENTED
329 PerformanceMonitor& operator=(const PerformanceMonitor&);
330
331 public:
332 // TYPES
333 enum Measure {
334 // Enumerates the set of performance measures this class is capable of
335 // monitoring.
336
337 e_CPU_TIME, // CPU time (seconds)
338 e_CPU_TIME_USER, // user CPU time (seconds)
339 e_CPU_TIME_SYSTEM, // system CPU time (seconds)
340 e_CPU_UTIL, // weighted CPU % (user + system)
341 e_CPU_UTIL_USER, // weighted user CPU %
342 e_CPU_UTIL_SYSTEM, // weighted system CPU %
343 e_RESIDENT_SIZE, // number of MBs of physical memory
344 e_NUM_THREADS, // number of threads
345 e_NUM_PAGEFAULTS, // number of pagefaults (major + minor)
346 e_VIRTUAL_SIZE, // number of MBs in the heap
348#ifndef BDE_OMIT_INTERNAL_DEPRECATED
371#endif // BDE_OMIT_INTERNAL_DEPRECATED
372 };
373
374 /// Defines the performance statistics collected for a monitored
375 /// process. Note that this class is not fully value-semantic. It is
376 /// intended to provide a read-only view of a set of collected
377 /// performance statistics.
378 ///
379 /// See @ref balb_performancemonitor
381
382 // FRIENDS
383 friend class Collector<OsType>;
384 // Grants write-access to the specific 'Collector' instantiation
385 // for the current platform.
386
387 // DATA
388 int d_pid;
389 // process identifier
390
391 bsl::string d_description;
392 // process description
393
394 bdlt::Datetime d_startTimeUtc;
395 // process start time, in UTC time
396
397 bsls::TimeInterval d_startTime;
398 // process start time, since the system
399 // epoch
400
401 double d_elapsedTime;
402 // time elapsed since process startup
403
404 bsls::AtomicInt d_numSamples;
405 // num samples taken
406
407 double d_lstData[e_NUM_MEASURES];
408 // latest collected data
409
410 double d_minData[e_NUM_MEASURES];
411 // min
412
413 double d_maxData[e_NUM_MEASURES];
414 // max
415
416 double d_totData[e_NUM_MEASURES];
417 // cumulative
418
419 mutable bslmt::RWMutex d_guard;
420 // serialize write access
421
422 private:
423 // NOT IMPLEMENTED
424 Statistics& operator=(const Statistics&);
425
426 public:
427 // TRAITS
430
431 // CREATORS
432
433 /// Create an instance of this class. Optionally specify a
434 /// `basicAllocator` used to supply memory. If `basicAllocator` is
435 /// 0, the currently installed default allocator is used.
436 explicit Statistics(bslma::Allocator *basicAllocator = 0);
437
438 /// Create a `Statistics` object aggregating the same statistics
439 /// values as the specified `original` object. Optionally specify a
440 /// `basicAllocator` used to supply memory. If `basicAllocator` is
441 /// 0, the currently installed default allocator is used.
442 Statistics(const Statistics& original,
443 bslma::Allocator *basicAllocator = 0);
444
445 // MANIPULATORS
446
447 /// Reset the min, max, and average values collected for each
448 /// measure.
449 void reset();
450
451 // ACCESSORS
452
453 /// Return the latest collected value for the specified `measure`.
454 double latestValue(Measure measure) const;
455
456 /// Return the minimum collected value for the specified `measure`.
457 double minValue(Measure measure) const;
458
459 /// Return the maximum collected value for the specified `measure`.
460 double maxValue(Measure measure) const;
461
462 /// Return the average of the collected values for the specified
463 /// `metric`.
464 double avgValue(Measure measure) const;
465
466 /// Return the pid for which these statistics were collected.
467 int pid() const;
468
469 /// Return the user-supplied description of the process identified
470 /// by the result of the `pid()` function.
471 const bsl::string& description() const;
472
473 /// Return the number of seconds (in wall time) that have elapsed
474 /// since the startup the process identified by the result of the
475 /// `pid()` function.
476 double elapsedTime() const;
477
478 /// Return the startup time in Coordinated Universal Time.
479 const bdlt::Datetime& startupTime() const;
480
481 /// Print all collected statistics to the specified `os` stream.
482 void print(bsl::ostream& os) const;
483
484 /// Print the specified `measure` to the specified `os` stream.
485 void print(bsl::ostream& os, Measure measure) const;
486
487 /// Print the specified `measureIdentifier` to the specified `os`
488 /// stream. The value of `measureIdentifier` should be a string
489 /// literal corresponding to the desired measure enumerator, e.g.,
490 /// `e_CPU_TIME`.
491 void print(bsl::ostream& os, const char *measureIdentifier) const;
492 };
493
494 /// Provide a mechanism that models the "Forward Iterator" concept over
495 /// a collection of non-modifiable performance statistics.
496 ///
497 /// See @ref balb_performancemonitor
499
500 // FRIENDS
501 friend class PerformanceMonitor; // grant access to the private
502 // constructor
503
504 // DATA
505 PidMap::const_iterator d_it; // wrapped iterator
506 bslmt::RWMutex *d_mapGuard_p; // serialize access to the map
507
508 // PRIVATE CREATORS
509
510 /// Create an instance of this class that wraps the specified `it`
511 /// iterator protected by the specified `mapGuard`.
513 bslmt::RWMutex *mapGuard);
514
515 public:
516 // TYPES
517
518 /// Defines a type alias for the tag type that represents the
519 /// iterator concept this class models.
520 typedef bsl::forward_iterator_tag iterator_category;
521
522 /// Defines a type alias for the type of the result of dereferencing
523 /// this iterator.
525
526 /// Defines a type alias for the type of the result of the
527 /// difference between the addresses of two value types.
528 typedef bsl::ptrdiff_t difference_type;
529
530 /// Defines a type alias for a pointer to this iterator's value
531 /// type.
532 typedef const Statistics* pointer;
533
534 /// Defines a type alias for a reference to this iterator's value
535 /// type.
536 typedef const Statistics& reference;
537
538 // CREATORS
539
540 /// Create an instance of this class having an invalid value.
542
543 // MANIPULATORS
544
545 /// Advance this iterator to refer to the next collection of
546 /// statistics for a monitored pid and return a reference to the
547 /// modifiable value type of this iterator. If there is no next
548 /// collection of statistics, this iterator will be set equal to
549 /// `end()`. The behavior of this function is undefined unless this
550 /// iterator is dereferenceable.
552
553 /// Advance this iterator to refer to the next collection of
554 /// statistics for a monitored pid and return the iterator pointing
555 /// to the previous modifiable value type. If there is no next
556 /// collection of statistics, this iterator will be set equal to
557 /// `end()`. The behavior of this function is undefined unless this
558 /// iterator is dereferenceable.
560
561 // ACCESSORS
562
563 /// Return a reference to the non-modifiable value type of this
564 /// iterator.
565 reference operator*() const;
566
567 /// Return a reference to the non-modifiable value type of this
568 /// iterator.
569 pointer operator->() const;
570
571 /// Return `true` if the specified `rhs` iterator points to the
572 /// same instance of the iterator's value type as "this" iterator,
573 /// and `false` otherwise. The behavior of this function is
574 /// undefined unless the `rhs` iterator and "this" iterator both
575 /// iterate over the same collection of Statistics.
576 bool operator==(const ConstIterator& rhs) const;
577
578 /// Return `true` if the specified `rhs` iterator does not point to
579 /// the same instance of the iterator's value type as "this"
580 /// iterator, and `false` otherwise. The behavior of this function
581 /// is undefined unless the `rhs` iterator and "this" iterator both
582 /// iterate over the same collection of Statistics.
583 bool operator!=(const ConstIterator& rhs) const;
584 };
585
586 // TRAITS
589
590 // CREATORS
591
592 /// Create an instance of this class to collect performance statistics
593 /// on demand (via the `collect` method). Optionally specify a
594 /// `basicAllocator` used to supply memory. If `basicAllocator` is 0,
595 /// the currently installed default allocator is used.
596 explicit
598
599 /// Create an instance of this class that uses the specified `scheduler`
600 /// to automatically collect performance statistics every specified
601 /// `interval` (specified in seconds). Optionally specify a
602 /// `basicAllocator` used to supply memory. If `basicAllocator` is 0,
603 /// the currently installed default allocator is used. Note that a
604 /// non-positive `interval` value indicates that performance statistics
605 /// should *not* be automatically collected--in this case the user is
606 /// responsible for manually calling the `collect` function.
608 double interval,
609 bslma::Allocator *basicAllocator = 0);
610
611 /// Destroy this object.
613
614 // MANIPULATORS
615
616 /// Register the specified process `pid` having the specified
617 /// user-defined `description` with this performance monitor. After
618 /// registration, performance statistics will be collected for the
619 /// `pid` upon invocation of the `collect` function. Note that a `pid`
620 /// value of zero is interpreted as the `pid` of the current process.
621 /// Return 0 on success or a non-zero value otherwise.
622 int registerPid(int pid, const bsl::string& description);
623
624 /// Unregister the specified process `pid` from the performance monitor.
625 /// After unregistration, to statistics for the `pid` will be no longer
626 /// be available unless the `pid` is re-registered with the performance
627 /// monitor through calling `registerPid`. Note that a `pid` value of
628 /// zero is interpreted as the `pid` of the current process. Return
629 /// 0 on success or a non-zero value otherwise.
630 int unregisterPid(int pid);
631
632 /// Set the specified time `interval`, in seconds, after which
633 /// statistics for each registered pid are automatically collected. The
634 /// behavior is undefined unless a scheduler was supplied at the
635 /// construction of this performance monitor. Note that a non-positive
636 /// `interval` value indicates that performance statistics should not be
637 /// automatically collected--in this case the user is responsible for
638 /// manually calling the `collect` function.
639 void setCollectionInterval(double interval);
640
641 /// Collect performance statistics for each registered pid.
642 void collect();
643
644 /// Reset the collected min, max, and average values collected for each
645 /// measure for each monitored process.
647
648 // ACCESSORS
649
650 /// Return an iterator positioned at the first set of collected
651 /// performance statistics.
652 ConstIterator begin() const;
653
654 /// Return an iterator that represents the end of the sequence of sets
655 /// of collected performance statistics.
656 ConstIterator end() const;
657
658 /// Return the iterator pointing to the set of collected performance
659 /// statistics for the specified `pid` if `pid` has been registered with
660 /// this performance monitor through the `registerPid` function,
661 /// otherwise return `end()`.
662 ConstIterator find(int pid) const;
663
664 /// Return the number of processes registered for statistics collection.
665 int numRegisteredPids() const;
666};
667
668#if defined(BSLS_PLATFORM_OS_LINUX) || defined(BSLS_PLATFORM_OS_CYGWIN)
669
670/// Describes the fields present in /proc/<pid>/stat. For a complete
671/// description of each field, see `man proc`.
672///
673/// Note that sizes of the data fields are defined in terms of scanf(3)
674/// format specifiers, such as %d, %lu or %c. There is no good way to know
675/// if %lu is 32-bit wide or 64-bit, because the code can be built in the
676/// -m32 mode making sizeof(unsigned long)==4 and executed on a 64bit
677/// platform where the kernel thinks that %lu can represent 64-bit wide
678/// integers. Therefore we use `Uint64` regardless of the build
679/// configuration.
680struct PerformanceMonitor_LinuxProcStatistics {
681
682 // PUBLIC TYPES
683 typedef bsls::Types::Int64 LdType;
684 typedef bsls::Types::Uint64 LuType;
685 typedef bsls::Types::Uint64 LluType;
686
687 // PUBLIC DATA
688 int d_pid; // process pid
689 bsl::string d_comm; // filename of executable
690 char d_state; // process state
691 int d_ppid; // process's parent pid
692 int d_pgrp; // process group id
693 int d_session; // process session id
694 int d_tty_nr; // the tty used by the process
695 int d_tpgid; // tty owner's group id
696 unsigned int d_flags; // kernel flags
697 LuType d_minflt; // num minor page faults
698 LuType d_cminflt; // num minor page faults - children
699 LuType d_majflt; // num major page faults
700 LuType d_cmajflt; // num major page faults - children
701 LuType d_utime; // num jiffies in user mode
702 LuType d_stime; // num jiffies in kernel mode
703 LdType d_cutime; // num jiffies, user mode, children
704 LdType d_cstime; // num jiffies, kernel mode, children
705 LdType d_priority; // standard nice value, plus fifteen
706 LdType d_nice; // nice value
707 LdType d_numThreads; // number of threads (since Linux 2.6)
708 LdType d_itrealvalue; // num jiffies before next SIGALRM
709 LluType d_starttime; // time in jiffies since system boot
710 LuType d_vsize; // virtual memory size, in bytes
711 LdType d_rss; // resident set size, in pages
712
713 // Note that subsequent fields present in '/proc/<pid>/stat' are not
714 // required for any collected measures.
715
716 // CLASS METHOD
717
718 /// For the specified process id `pid`, load the contents of the file
719 /// `/proc/<pid>/stat` into the specified `buffer`. Return 0 on success
720 /// and a non-zero value otherwise.
721 static int readProcStatString(bsl::string *buffer, int pid);
722
723 private:
724 // NOT IMPLEMENTED
725
726 public:
727 // CREATORS
728
729 /// Default construct all fields in this object.
730 PerformanceMonitor_LinuxProcStatistics();
731
732 // PerformanceMonitor_LinuxProcStatistics(
733 // const PerformanceMonitor_LinuxProcStatistics&) = default;
734
735 // MANIPULATORS
736 // PerformanceMonitor_LinuxProcStatistics& operator=(
737 // const PerformanceMonitor_LinuxProcStatistics& rhs) = default;
738 // Copy all fields of the specified 'rhs' to this object, and return a
739 // reference to it.
740
741 /// Parse the specified `procStatString` and populate all the fields in
742 /// this `struct`. Check that the specified `pid` matches the `pid`
743 /// field in the string. Return 0 on success and a non-zero value
744 /// otherwise.
745 int parseProcStatString(const bsl::string& procStatString, int pid);
746};
747
748#endif
749
750// ============================================================================
751// INLINE DEFINITIONS
752// ============================================================================
753
754 // ---------------------------------------
755 // class PerformanceMonitor::ConstIterator
756 // ---------------------------------------
757
758// CREATORS
759inline
764
765inline
768 bslmt::RWMutex *mapGuard)
769: d_it(it)
770, d_mapGuard_p(mapGuard)
771{
772}
773
774// ACCESSORS
775inline
778{
779 bslmt::ReadLockGuard<bslmt::RWMutex> guard(d_mapGuard_p);
780 return *d_it->second.first;
781}
782
783inline
786{
787 bslmt::ReadLockGuard<bslmt::RWMutex> guard(d_mapGuard_p);
788 return d_it->second.first.get();
789}
790
791// MANIPULATORS
792inline
795{
796 bslmt::ReadLockGuard<bslmt::RWMutex> guard(d_mapGuard_p);
797 ++d_it;
798 return *this;
799}
800
801inline
804{
806 ++*this;
807 return temp;
808}
809
810// ACCESSORS
811inline
813 const ConstIterator& rhs) const
814{
815 return d_it == rhs.d_it;
816}
817
818inline
820 const ConstIterator& rhs) const
821{
822 return d_it != rhs.d_it;
823}
824
825 // ------------------------------------
826 // class PerformanceMonitor::Statistics
827 // ------------------------------------
828
829// ACCESSORS
830inline
832{
833 BSLS_ASSERT_SAFE(measure >= 0 && measure < e_NUM_MEASURES);
834
836 return d_lstData[measure];
837}
838
839inline
841{
842 BSLS_ASSERT_SAFE(measure >= 0 && measure < e_NUM_MEASURES);
843
845 return d_minData[measure];
846}
847
848inline
850{
851 BSLS_ASSERT_SAFE(measure >= 0 && measure < e_NUM_MEASURES);
852
854 return d_maxData[measure];
855}
856
857inline
859{
860 BSLS_ASSERT_SAFE(measure >= 0 && measure < e_NUM_MEASURES);
861
863 return d_totData[measure] / d_numSamples;
864}
865
866inline
868{
869 return d_pid;
870}
871
872inline
874{
875 return d_description;
876}
877
878inline
880{
882 return d_elapsedTime;
883}
884
885inline
887{
888 return d_startTimeUtc;
889}
890
891 // ------------------------
892 // class PerformanceMonitor
893 // ------------------------
894
895// ACCESSORS
896inline
899{
900 bslmt::ReadLockGuard<bslmt::RWMutex> guard(&d_mapGuard);
901 return ConstIterator(d_pidMap.begin(), &d_mapGuard);
902}
903
904inline
907{
908 bslmt::ReadLockGuard<bslmt::RWMutex> guard(&d_mapGuard);
909 return ConstIterator(d_pidMap.end(), &d_mapGuard);
910}
911
912inline
915{
916 bslmt::ReadLockGuard<bslmt::RWMutex> guard(&d_mapGuard);
917 return ConstIterator(d_pidMap.find(pid), &d_mapGuard);
918}
919
920inline
921int
923{
924 bslmt::ReadLockGuard<bslmt::RWMutex> guard(&d_mapGuard);
925 return static_cast<int>(d_pidMap.size());
926}
927
928} // close package namespace
929
930
931#endif
932
933// ----------------------------------------------------------------------------
934// Copyright 2018 Bloomberg Finance L.P.
935//
936// Licensed under the Apache License, Version 2.0 (the "License");
937// you may not use this file except in compliance with the License.
938// You may obtain a copy of the License at
939//
940// http://www.apache.org/licenses/LICENSE-2.0
941//
942// Unless required by applicable law or agreed to in writing, software
943// distributed under the License is distributed on an "AS IS" BASIS,
944// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
945// See the License for the specific language governing permissions and
946// limitations under the License.
947// ----------------------------- END-OF-FILE ----------------------------------
948
949/** @} */
950/** @} */
951/** @} */
Definition balb_performancemonitor.h:498
const Statistics & reference
Definition balb_performancemonitor.h:536
bsl::forward_iterator_tag iterator_category
Definition balb_performancemonitor.h:520
const Statistics * pointer
Definition balb_performancemonitor.h:532
bool operator!=(const ConstIterator &rhs) const
Definition balb_performancemonitor.h:819
reference operator*() const
Definition balb_performancemonitor.h:777
pointer operator->() const
Definition balb_performancemonitor.h:785
bool operator==(const ConstIterator &rhs) const
Definition balb_performancemonitor.h:812
ConstIterator()
Create an instance of this class having an invalid value.
Definition balb_performancemonitor.h:760
ConstIterator & operator++()
Definition balb_performancemonitor.h:794
Statistics value_type
Definition balb_performancemonitor.h:524
bsl::ptrdiff_t difference_type
Definition balb_performancemonitor.h:528
Definition balb_performancemonitor.h:380
Statistics(const Statistics &original, bslma::Allocator *basicAllocator=0)
Statistics(bslma::Allocator *basicAllocator=0)
double minValue(Measure measure) const
Return the minimum collected value for the specified measure.
Definition balb_performancemonitor.h:840
const bsl::string & description() const
Definition balb_performancemonitor.h:873
void print(bsl::ostream &os) const
Print all collected statistics to the specified os stream.
double avgValue(Measure measure) const
Definition balb_performancemonitor.h:858
void print(bsl::ostream &os, Measure measure) const
Print the specified measure to the specified os stream.
double maxValue(Measure measure) const
Return the maximum collected value for the specified measure.
Definition balb_performancemonitor.h:849
double elapsedTime() const
Definition balb_performancemonitor.h:879
int pid() const
Return the pid for which these statistics were collected.
Definition balb_performancemonitor.h:867
double latestValue(Measure measure) const
Return the latest collected value for the specified measure.
Definition balb_performancemonitor.h:831
BSLMF_NESTED_TRAIT_DECLARATION(Statistics, bslma::UsesBslmaAllocator)
void print(bsl::ostream &os, const char *measureIdentifier) const
const bdlt::Datetime & startupTime() const
Return the startup time in Coordinated Universal Time.
Definition balb_performancemonitor.h:886
Definition balb_performancemonitor.h:251
int registerPid(int pid, const bsl::string &description)
ConstIterator end() const
Definition balb_performancemonitor.h:906
BSLMF_NESTED_TRAIT_DECLARATION(PerformanceMonitor, bslma::UsesBslmaAllocator)
~PerformanceMonitor()
Destroy this object.
PerformanceMonitor(bslma::Allocator *basicAllocator=0)
void collect()
Collect performance statistics for each registered pid.
ConstIterator find(int pid) const
Definition balb_performancemonitor.h:914
ConstIterator begin() const
Definition balb_performancemonitor.h:898
void setCollectionInterval(double interval)
int unregisterPid(int pid)
Measure
Definition balb_performancemonitor.h:333
@ e_CPU_UTIL_USER
Definition balb_performancemonitor.h:341
@ BAEA_CPU_TIME_USER
Definition balb_performancemonitor.h:350
@ BAEA_CPU_TIME_SYSTEM
Definition balb_performancemonitor.h:351
@ CPU_UTIL_SYSTEM
Definition balb_performancemonitor.h:365
@ RESIDENT_SIZE
Definition balb_performancemonitor.h:366
@ e_RESIDENT_SIZE
Definition balb_performancemonitor.h:343
@ BAEA_CPU_UTIL
Definition balb_performancemonitor.h:352
@ NUM_THREADS
Definition balb_performancemonitor.h:367
@ CPU_UTIL_USER
Definition balb_performancemonitor.h:364
@ e_CPU_UTIL
Definition balb_performancemonitor.h:340
@ BAEA_CPU_UTIL_SYSTEM
Definition balb_performancemonitor.h:354
@ e_CPU_TIME_SYSTEM
Definition balb_performancemonitor.h:339
@ e_NUM_MEASURES
Definition balb_performancemonitor.h:347
@ e_CPU_UTIL_SYSTEM
Definition balb_performancemonitor.h:342
@ CPU_TIME_SYSTEM
Definition balb_performancemonitor.h:362
@ NUM_PAGEFAULTS
Definition balb_performancemonitor.h:368
@ e_CPU_TIME
Definition balb_performancemonitor.h:337
@ e_NUM_THREADS
Definition balb_performancemonitor.h:344
@ CPU_TIME
Definition balb_performancemonitor.h:360
@ BAEA_NUM_THREADS
Definition balb_performancemonitor.h:356
@ BAEA_CPU_UTIL_USER
Definition balb_performancemonitor.h:353
@ VIRTUAL_SIZE
Definition balb_performancemonitor.h:369
@ BAEA_VIRTUAL_SIZE
Definition balb_performancemonitor.h:358
@ NUM_MEASURES
Definition balb_performancemonitor.h:370
@ BAEA_RESIDENT_SIZE
Definition balb_performancemonitor.h:355
@ BAEA_CPU_TIME
Definition balb_performancemonitor.h:349
@ e_VIRTUAL_SIZE
Definition balb_performancemonitor.h:346
@ e_NUM_PAGEFAULTS
Definition balb_performancemonitor.h:345
@ BAEA_NUM_MEASURES
Definition balb_performancemonitor.h:359
@ CPU_TIME_USER
Definition balb_performancemonitor.h:361
@ BAEA_NUM_PAGEFAULTS
Definition balb_performancemonitor.h:357
@ CPU_UTIL
Definition balb_performancemonitor.h:363
@ e_CPU_TIME_USER
Definition balb_performancemonitor.h:338
PerformanceMonitor(bdlmt::TimerEventScheduler *scheduler, double interval, bslma::Allocator *basicAllocator=0)
int numRegisteredPids() const
Return the number of processes registered for statistics collection.
Definition balb_performancemonitor.h:922
Definition bdlmt_timereventscheduler.h:434
int Handle
Definition bdlmt_timereventscheduler.h:492
Definition bdlt_datetime.h:331
Definition bslstl_string.h:1281
Definition bslstl_map.h:619
BloombergLP::bslstl::TreeIterator< const value_type, Node, difference_type > const_iterator
Definition bslstl_map.h:724
iterator end() BSLS_KEYWORD_NOEXCEPT
Definition bslstl_map.h:2759
iterator find(const key_type &key)
Definition bslstl_map.h:1542
size_type size() const BSLS_KEYWORD_NOEXCEPT
Return the number of elements in this map.
Definition bslstl_map.h:3518
iterator begin() BSLS_KEYWORD_NOEXCEPT
Definition bslstl_map.h:2751
Definition bslstl_sharedptr.h:1830
Definition bslma_allocator.h:457
Definition bslmt_rwmutex.h:147
Definition bslmt_readlockguard.h:287
Definition bsls_atomic.h:743
Definition bsls_timeinterval.h:301
#define BSLS_ASSERT_SAFE(X)
Definition bsls_assert.h:1762
#define BSLS_IDENT(str)
Definition bsls_ident.h:195
Definition balb_controlmanager.h:133
Definition bslma_usesbslmaallocator.h:343
unsigned long long Uint64
Definition bsls_types.h:137
long long Int64
Definition bsls_types.h:132