Exemplo n.º 1
0
        static float[] ExtractSamples(int categoryIndex, string counter, InstanceDataCollectionCollection[][] samples, string instance)
        {
            float[]       result    = new float[samples.Length - 1];
            CounterSample oldSample = CounterSample.Empty;

            for (int i = 0; i < samples.Length; i++)
            {
                InstanceDataCollectionCollection idcc = samples[i][categoryIndex];
                if (idcc == null)
                {
                    return(null);
                }
                InstanceDataCollection idc = idcc[counter];
                if (idc == null)
                {
                    return(null);
                }
                InstanceData id = idc[instance];
                if (id == null)
                {
                    id = idc[TruncatedAppName(instance)];
                    if (id == null)
                    {
                        return(null);
                    }
                }
                CounterSample sample = id.Sample;
                if (i > 0)
                {
                    result[i - 1] = Calculate(oldSample, sample);
                }
                oldSample = sample;
            }
            return(result);
        }
Exemplo n.º 2
0
        protected override void PerformMainLoopService()
        {
            if (sampleIntervalTimer.Started != BaseState.IsOnline)
            {
                if (BaseState.IsOnline)
                {
                    sampleIntervalTimer.Reset(triggerImmediately: true);
                }
                else
                {
                    sampleIntervalTimer.Stop();
                }
            }

            bool sampleIntervalTimerTriggered = sampleIntervalTimer.IsTriggered;

            if (sampleIntervalTimerTriggered)
            {
                try
                {
                    foreach (var tuple in pccTupleArray)
                    {
                        InstanceDataCollectionCollection categorySample = tuple.Item1.ReadCategory();
                        tuple.Item2.DoForEach(pct => pct.Service(Log, categorySample));
                    }

                    mdrfWriter.RecordGroups();
                }
                catch (System.Exception ex)
                {
                    Log.Debug.Emit("{0} generated unexpected exception: {1}", CurrentMethodName, ex.ToString(ExceptionFormat.TypeAndMessage));
                }
            }
        }
Exemplo n.º 3
0
            public Dictionary <string, float> Refresh(float minValue)
            {
                InstanceDataCollectionCollection allData = TryGetPerformanceData(() => this.category.ReadCategory(), out Exception ex);

                Dictionary <string, float> result = new Dictionary <string, float>(StringComparer.CurrentCultureIgnoreCase);

                if (allData != null)
                {
                    InstanceDataCollection processData = allData["% Processor Time"];
                    if (processData != null)
                    {
                        Dictionary <string, CounterSample> currentSamples = new Dictionary <string, CounterSample>();
                        foreach (InstanceData data in processData.Values)
                        {
                            string        instanceName  = data.InstanceName;
                            CounterSample currentSample = data.Sample;
                            currentSamples[instanceName] = currentSample;

                            if (this.previousSamples != null && this.previousSamples.TryGetValue(instanceName, out CounterSample previousSample))
                            {
                                // We have to average the usage across all the logical processors.
                                // On an 8 processor machine, the counter can return up to 800!
                                float value = CounterSampleCalculator.ComputeCounterValue(previousSample, currentSample) / ProcessorCount;
                                result[data.InstanceName] = value >= minValue ? value : float.NaN;
                            }
                        }

                        this.previousSamples = currentSamples;
                    }
                }

                return(result);
            }
Exemplo n.º 4
0
        public static void PerformanceCounterCategory_ReadCategory()
        {
            PerformanceCounterCategory pcc = Helpers.RetryOnAllPlatforms(() => new PerformanceCounterCategory("Processor"));

            InstanceDataCollectionCollection idColCol = pcc.ReadCategory();

            Assert.NotNull(idColCol);
        }
Exemplo n.º 5
0
        public static void InstanceDataCollectionCollection_CopyTo()
        {
            InstanceDataCollectionCollection idcc = GetInstanceDataCollectionCollection();

            InstanceDataCollection[] idc = new InstanceDataCollection[idcc.Values.Count];
            idcc.CopyTo(idc, 0);
            Assert.True(idc.Length > 0);
        }
Exemplo n.º 6
0
        private static string FindProcessInstance(int pid, IEnumerable <string> instances, string categoryName, string counterName)
        {
            Tuple <DateTime, PerformanceCounterCategory, InstanceDataCollectionCollection> cached;

            DateTime utcNow = DateTime.UtcNow;

            InstanceDataCollectionCollection result = null;

            PerformanceCounterCategory category = null;

            if (cache.TryGetValue(categoryName, out cached))
            {
                category = cached.Item2;

                if (cached.Item1 < utcNow)
                {
                    result = cached.Item3;
                }
            }

            if (result == null)
            {
                if (category == null)
                {
                    category = new PerformanceCounterCategory(categoryName);
                }

                result = category.ReadCategory();

                cache.TryAdd(categoryName, new Tuple <DateTime, PerformanceCounterCategory, InstanceDataCollectionCollection>(utcNow.AddMinutes(1), category, result));
            }

            InstanceDataCollection counters = result[counterName];

            if (counters != null)
            {
                foreach (string i in instances)
                {
                    InstanceData instance = counters[i];

                    if ((instance != null) && (pid == instance.RawValue))
                    {
                        return(i);
                    }
                }
            }

            return(null);
        }
Exemplo n.º 7
0
 static InstanceDataCollectionCollection[] SampleCategories(PerformanceCounterCategory[] categories)
 {
     InstanceDataCollectionCollection[] idcc = new InstanceDataCollectionCollection[categories.Length];
     for (int i = 0; i < categories.Length; i++)
     {
         try
         {
             idcc[i] = categories[i].ReadCategory();
         }
         catch (Exception)
         {
         }
     }
     return(idcc);
 }
Exemplo n.º 8
0
            public void Service(Logging.IBasicLogger logger, InstanceDataCollectionCollection categorySample, bool rethrow = false)
            {
                if (!isUsable)
                {
                    return;
                }

                try
                {
                    InstanceDataCollection instanceDataCollection = categorySample[pcs.CounterName];
                    InstanceData           instanceData           = instanceDataCollection[pcs.InstanceName.MapNullToEmpty()]; // use empty string for counters that only have one value

                    CounterSample counterSample = instanceData.Sample;

                    if (!useRawPerfCtrValue)
                    {
                        gpInfo.VC = new ValueContainer(CounterSample.Calculate(lastCounterSample, counterSample));
                    }
                    else
                    {
                        gpInfo.VC = new ValueContainer(counterSample.RawValue);
                    }

                    lastCounterSample = counterSample;

                    logExceptionElevationHoldoffTimer.StopIfNeeded();
                }
                catch (System.Exception ex)
                {
                    bool useHighLevelMesg = (logExceptionElevationHoldoffTimer.IsTriggered || !logExceptionElevationHoldoffTimer.Started);
                    logExceptionElevationHoldoffTimer.StartIfNeeded();

                    Logging.IMesgEmitter emitter = (logger == null ? Logging.NullEmitter : (useHighLevelMesg ? logger.Info : logger.Trace));

                    emitter.Emit("{0} for '{1}' generated exception: {2}", CurrentMethodName, gpInfo.Name, ex.ToString(ExceptionFormat.TypeAndMessage));
                }
            }
Exemplo n.º 9
0
        public static void InstanceDataCollectionCollection_GetValues()
        {
            InstanceDataCollectionCollection idcc = GetInstanceDataCollectionCollection();

            Assert.True(idcc.Values.Count > 0);
        }
Exemplo n.º 10
0
        public static void InstanceDataCollectionCollection_GetItem_Invalid()
        {
            InstanceDataCollectionCollection idcc = GetInstanceDataCollectionCollection();

            Assert.Throws <ArgumentNullException>(() => idcc[null]);
        }
Exemplo n.º 11
0
        public static InstanceDataCollection GetInstanceDataCollection()
        {
            InstanceDataCollectionCollection idcc = GetInstanceDataCollectionCollection();

            return(idcc["% User Time"]);
        }
Exemplo n.º 12
0
        public static void InstanceDataCollectionCollection_Contains_inValid()
        {
            InstanceDataCollectionCollection idcc = GetInstanceDataCollectionCollection();

            Assert.Throws <ArgumentNullException>(() => idcc.Contains(null));
        }
Exemplo n.º 13
0
        public static void InstanceDataCollectionCollection_Contains_Valid()
        {
            InstanceDataCollectionCollection idcc = GetInstanceDataCollectionCollection();

            Assert.False(idcc.Contains("Not a real instance"));
        }
Exemplo n.º 14
0
    //</snippet7>

    public static void Main()
    {
        string catNumStr;
        int    categoryNum;

        PerformanceCounterCategory[] categories = PerformanceCounterCategory.GetCategories();

        // Create and sort an array of category names.
        string[] categoryNames = new string[categories.Length];
        int      catX;

        for (catX = 0; catX < categories.Length; catX++)
        {
            categoryNames[catX] = categories[catX].CategoryName;
        }
        Array.Sort(categoryNames);

        Console.WriteLine("These categories are registered on this computer:");

        for (catX = 0; catX < categories.Length; catX++)
        {
            Console.WriteLine("{0,4} - {1}", catX + 1, categoryNames[catX]);
        }

        // Ask the user to choose a category.
        Console.Write("Enter the category number from the above list: ");
        catNumStr = Console.ReadLine();

        // Validate the entered category number.
        try
        {
            categoryNum = int.Parse(catNumStr);
            if (categoryNum < 1 || categoryNum > categories.Length)
            {
                throw new Exception(String.Format("The category number must be in the " +
                                                  "range 1..{0}.", categories.Length));
            }
            categoryName = categoryNames[(categoryNum - 1)];
        }
        catch (Exception ex)
        {
            Console.WriteLine("\"{0}\" is not a valid category number." +
                              "\r\n{1}", catNumStr, ex.Message);
            return;
        }
        //<snippet5>
        //<snippet6>

        // Process the InstanceDataCollectionCollection for this category.
        PerformanceCounterCategory       pcc      = new PerformanceCounterCategory(categoryName);
        InstanceDataCollectionCollection idColCol = pcc.ReadCategory();

        InstanceDataCollection[] idColArray = new InstanceDataCollection[idColCol.Count];

        Console.WriteLine("InstanceDataCollectionCollection for \"{0}\" " +
                          "has {1} elements.", categoryName, idColCol.Count);
        //</snippet6>

        // Copy and process the InstanceDataCollection array.
        idColCol.CopyTo(idColArray, 0);

        foreach (InstanceDataCollection idCol in idColArray)
        {
            ProcessInstanceDataCollection(idCol);
        }
        //</snippet5>
    }
Exemplo n.º 15
0
    public static void Main()
    {
        string catNumStr;
        int    categoryNum;

        PerformanceCounterCategory[] categories = PerformanceCounterCategory.GetCategories();

        Console.WriteLine("These categories are registered on this computer:");

        int catX;

        for (catX = 0; catX < categories.Length; catX++)
        {
            Console.WriteLine("{0,4} - {1}", catX + 1, categories[catX].CategoryName);
        }

        // Ask the user to choose a category.
        Console.Write("Enter the category number from the above list: ");
        catNumStr = Console.ReadLine();

        // Validate the entered category number.
        try
        {
            categoryNum = int.Parse(catNumStr);
            if (categoryNum < 1 || categoryNum > categories.Length)
            {
                throw new Exception(String.Format("The category number must be in the " +
                                                  "range 1..{0}.", categories.Length));
            }
            categoryName = categories[(categoryNum - 1)].CategoryName;
        }
        catch (Exception ex)
        {
            Console.WriteLine("\"{0}\" is not a valid category number." +
                              "\r\n{1}", catNumStr, ex.Message);
            return;
        }

        // Process the InstanceDataCollectionCollection for this category.
        PerformanceCounterCategory       pcc      = new PerformanceCounterCategory(categoryName);
        InstanceDataCollectionCollection idColCol = pcc.ReadCategory();

        ICollection idColColKeys = idColCol.Keys;

        string[] idCCKeysArray = new string[idColColKeys.Count];
        idColColKeys.CopyTo(idCCKeysArray, 0);

        ICollection idColColValues = idColCol.Values;

        InstanceDataCollection[] idCCValuesArray = new InstanceDataCollection[idColColValues.Count];
        idColColValues.CopyTo(idCCValuesArray, 0);

        Console.WriteLine("InstanceDataCollectionCollection for \"{0}\" " +
                          "has {1} elements.", categoryName, idColCol.Count);

        // Display the InstanceDataCollectionCollection Keys and Values.
        // The Keys and Values collections have the same number of elements.
        int index;

        for (index = 0; index < idCCKeysArray.Length; index++)
        {
            Console.WriteLine("  Next InstanceDataCollectionCollection " +
                              "Key is \"{0}\"", idCCKeysArray[index]);
            ProcessInstanceDataCollection(idCCValuesArray[index]);
        }
    }
Exemplo n.º 16
0
    //<snippet2>
    public static void Main(string[] args)
    {
        // These values can be used as arguments.
        string categoryName = "Process";
        string counterName  = "Private Bytes";
        string instanceName = "Explorer";

        InstanceDataCollection idCol;
        const string           SINGLE_INSTANCE_NAME = "systemdiagnosticsperfcounterlibsingleinstance";

        // Copy the supplied arguments into the local variables.
        try
        {
            categoryName = args[0];
            counterName  = args[1];
            instanceName = args[2];
        }
        catch
        {
            // Ignore the exception from non-supplied arguments.
        }

        try
        {
            // Get the InstanceDataCollectionCollection for this category.
            PerformanceCounterCategory       pcc      = new PerformanceCounterCategory(categoryName);
            InstanceDataCollectionCollection idColCol = pcc.ReadCategory();

            // Get the InstanceDataCollection for this counter.
            idCol = idColCol[counterName];
            if (idCol == null)
            {
                throw new Exception("Counter does not exist.");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("An error occurred getting the InstanceDataCollection for " +
                              "category \"{0}\", counter \"{1}\"." + "\n" + ex.Message, categoryName, counterName);
            return;
        }

        // If the instance name is empty, use the single-instance name.
        if (instanceName.Length == 0)
        {
            instanceName = SINGLE_INSTANCE_NAME;
        }

        //<snippet3>
        // Check if this instance name exists using the Contains
        // method of the InstanceDataCollection.
        if (!idCol.Contains(instanceName))
        //</snippet3>
        {
            Console.WriteLine("Instance \"{0}\" does not exist in counter \"{1}\", " +
                              "category \"{2}\".", instanceName, counterName, categoryName);
            return;
        }
        else
        {
            //<snippet4>
            // The instance name exists, now get its InstanceData object
            // using the indexer (Item property) for the InstanceDataCollection.
            InstanceData instData = idCol[instanceName];
            //</snippet4>

            Console.WriteLine("CategoryName: {0}", categoryName);
            Console.WriteLine("CounterName:  {0}", counterName);
            Console.WriteLine("InstanceName: {0}", instData.InstanceName);
            Console.WriteLine("RawValue:     {0}", instData.RawValue);
        }
    }
Exemplo n.º 17
0
        public void Update()
        {
            foreach (string categoryName in subscribers.Select(kvp => kvp.Key.Item1).Distinct())
            {
                PerformanceCounterCategory pcc = new PerformanceCounterCategory(categoryName);

                #if DEBUG
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();
                #endif

                InstanceDataCollectionCollection idcc = pcc.ReadCategory();

                #if DEBUG
                stopwatch.Stop();
                Console.WriteLine("{0:f4} ms\t{1}", stopwatch.Elapsed.TotalMilliseconds, categoryName);
                #endif

                foreach (InstanceDataCollection idc in idcc.Values)
                {
                    string counterName           = idc.CounterName;
                    Tuple <string, string> tuple = Tuple.Create(categoryName, counterName);

                    List <IPerfmonCallback> list;
                    if (subscribers.TryGetValue(tuple, out list))
                    {
                        List <Instance> instances = new List <Instance>();
                        DateTime?       timestamp = null;

                        foreach (InstanceData id in idc.Values)
                        {
                            string instanceName = (pcc.CategoryType == PerformanceCounterCategoryType.MultiInstance ? id.InstanceName : "*");
                            string path         = string.Format(@"\{0}({1})\{2}", categoryName, instanceName, counterName);

                            CounterSample sample = id.Sample;

                            if (timestamp == null)
                            {
                                timestamp = DateTime.FromFileTime(sample.TimeStamp100nSec);
                            }

                            CounterSample prevSample;
                            if (prevSamples.TryGetValue(path, out prevSample))
                            {
                                float value = CounterSample.Calculate(prevSample, sample);
                                instances.Add(new Instance()
                                {
                                    Name = instanceName, Value = value
                                });
                            }
                            prevSamples[path] = sample;
                        }

                        // If there are instances available but we don't have a previous sample
                        // to calculate their value, then don't send anything to the client yet
                        if (idc.Count > 0 && instances.Count == 0)
                        {
                            continue;
                        }

                        // Otherwise let the client know that there are no instances by sending
                        // an empty list with the current time
                        if (timestamp == null)
                        {
                            timestamp = DateTime.Now;
                        }

                        Counter counter = new Counter()
                        {
                            Name = counterName, Instances = instances
                        };
                        Category category = new Category()
                        {
                            Name = categoryName, Counters = new List <Counter>()
                            {
                                counter
                            }
                        };
                        EventData e = new EventData()
                        {
                            Category = category, Timestamp = timestamp.Value
                        };

                        ThreadPool.QueueUserWorkItem(_ =>
                        {
                            Parallel.ForEach(list, subscriber =>
                            {
                                try
                                {
                                    subscriber.OnNext(e);
                                }
                                catch (CommunicationException) { }
                            });
                        });
                    }
                }
            }
        }
Exemplo n.º 18
0
        static void Main(string[] args)
        {
            bool doModuleList    = true;
            bool doWorkingSet    = true;
            int  measurementTime = 10 /*secs*/;

            string[] configCounters = ReadConfigCounters("PerfStats.cfg");
            Console.WriteLine();

            // print usage information
            if (args.Length == 1 && (args[0] == "/?" || args[0].ToLower(CultureInfo.InvariantCulture) == "/help" ||
                                     args[0] == "-?" || args[0].ToLower(CultureInfo.InvariantCulture) == "-help"))
            {
                Usage();
                return;
            }

            // process command line

            string  processName = null;
            int     processId   = 0;
            Process process     = null;

            for (int i = 0; i < args.Length; i++)
            {
                // Can it be an option?
                if (args[i].Length >= 1 && (args[i][0] == '-' || args[i][0] == '/'))
                {
                    switch (args[i].Substring(1).ToLower(CultureInfo.InvariantCulture))
                    {
                    case    "m":
                    case    "m+":
                        doModuleList = true;
                        break;

                    case    "m-":
                        doModuleList = false;
                        break;

                    case    "p":
                        i++;
                        if (i < args.Length)
                        {
                            processId = Int32.Parse(args[i]);
                            process   = Process.GetProcessById(processId);
                            if (process == null)
                            {
                                Console.WriteLine("Process id not found: {0}", processId);
                            }
                            else
                            {
                                processName = process.MainModule.ModuleName;
                                if (processName.EndsWith(".exe") || processName.EndsWith(".EXE"))
                                {
                                    processName = processName.Substring(0, processName.Length - 4);
                                }
                                processName = FindProcessById(processName, processId);
                            }
                        }
                        else
                        {
                            Console.WriteLine("-P option missing argument");
                        }
                        break;

                    case    "w":
                    case    "w+":
                        doWorkingSet = true;
                        break;

                    case    "w-":
                        doWorkingSet = true;
                        break;

                    case    "t":
                        i++;
                        if (i < args.Length)
                        {
                            measurementTime = Int32.Parse(args[i]);
                            if (measurementTime < 1)
                            {
                                Console.WriteLine("Measurement time must be at least 1 seconds");
                                measurementTime = 1;
                            }
                        }
                        else
                        {
                            Console.WriteLine("-T option missing argument");
                        }
                        break;

                    default:
                        Console.WriteLine("Unrecognized option {0}", args[i]);
                        break;
                    }
                }
                else
                {
                    if (processName != null || processId != 0)
                    {
                        Console.WriteLine("More than one process specified");
                    }
                    else
                    {
                        processName = args[i];
                        if (processName.ToLower(CultureInfo.InvariantCulture).EndsWith(".exe"))
                        {
                            processName = processName.Substring(0, processName.Length - 4);
                        }
                    }
                }
            }

            if (processName != null)
            {
                if (process == null)
                {
                    processId = ProcessId(processName);
                    if (processId >= 0)
                    {
                        process = Process.GetProcessById(processId);
                    }
                }

                if (process == null)
                {
                    Console.WriteLine("Process {0} not found", processName);
                }
            }

            if (process == null)
            {
                MakeApplyToAllInstances(stdCounters);
                MakeApplyToAllInstances(configCounters);
            }

            long      startCycleCount = GetCycleCount64();
            int       startTickCount  = GetTickCount();
            Hashtable categoryHash    = new Hashtable();

            AddCategories(categoryHash, stdCounters);
            AddCategories(categoryHash, configCounters);

            PerformanceCounterCategory[] categories = new PerformanceCounterCategory[categoryHash.Count];
            int j = 0;

            foreach (PerformanceCounterCategory pcc in categoryHash.Values)
            {
                categories[j++] = pcc;
            }

            InstanceDataCollectionCollection[][] samples = new InstanceDataCollectionCollection[measurementTime + 1][];
            Console.Write("Taking measurements for {0} seconds: ", measurementTime);
            samples[0] = SampleCategories(categories);
            for (int t = 1; t <= measurementTime; t++)
            {
                System.Threading.Thread.Sleep(1000);
                samples[t] = SampleCategories(categories);
                Console.Write("{0}", (char)((t % 10) + '0'));
            }
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("System information:");
            Console.WriteLine("===================");
            PrintSystemInformation();

            long   elapsedCycleCount = GetCycleCount64() - startCycleCount;
            int    elapsedTickCount  = GetTickCount() - startTickCount;
            double clockSpeed        = (double)elapsedCycleCount / elapsedTickCount / 1000.0;

            Console.WriteLine("{0,-41}{1,7:n0} MHz", "Clock speed:", clockSpeed);
            int l2CacheSize = GetL2CacheSize();

            if (l2CacheSize == 0)
            {
                Console.WriteLine("{0,-41}{1,11}", "L2 Cache size:", "Unknown");
            }
            else
            {
                Console.WriteLine("{0,-41}{1,8:n0} kB", "L2 Cache size:", l2CacheSize / 1024);
            }

            PrintCounters(stdCounters, categories, samples, null);
            PrintCounters(configCounters, categories, samples, null);

            if (process != null)
            {
                Console.WriteLine();
                Console.WriteLine("Process information for {0}:", processName);
                Console.WriteLine("========================{0}=", new string('=', processName.Length));
                PrintCounters(stdCounters, categories, samples, processName);
                PrintCounters(configCounters, categories, samples, processName);

                if (doModuleList)
                {
                    PrintModuleList(process);
                }
                if (doWorkingSet)
                {
                    WorkingSetAnalysis(process, processName);
                }
            }
        }