예제 #1
1
    /// <summary>
    /// Return Download Speed in MBs
    /// </summary>
    /// <param name="lInstance">Network Interface ID</param>
    /// <param name="lDelay">Delay in seconds for more precision</param>
    /// <returns></returns>
    public static float GetDownloadSpeed(int lInstance = 1, int lDelay = 1)
    {
        PerformanceCounterCategory performanceCounterCategory = new PerformanceCounterCategory("Network Interface");
        string networkInstance = performanceCounterCategory.GetInstanceNames()[lInstance];

        PerformanceCounter performanceCounterReceived = new PerformanceCounter("Network Interface", "Bytes Received/sec", networkInstance);

        performanceCounterReceived.NextValue();
        Thread.Sleep(lDelay * 1000);
        float downloadSpeed = performanceCounterReceived.NextValue() / (1024f * 1024f);
        return downloadSpeed;
    }
        public static bool TryGetInstanceName(Process process, out string instanceName)
        {
            try
            {
                PerformanceCounterCategory processCategory = new PerformanceCounterCategory(CategoryName);
                string[] instanceNames = processCategory.GetInstanceNames();
                foreach (string name in instanceNames)
                {
                    if (name.StartsWith(process.ProcessName))
                    {
                        using (
                            PerformanceCounter processIdCounter = new PerformanceCounter(CategoryName, ProcessIdCounter,
                                name, true))
                        {
                            if (process.Id == (int) processIdCounter.RawValue)
                            {
                                instanceName = name;
                                return true;
                            }
                        }
                    }
                }

                instanceName = null;
                return false;
            }
            catch
            {
                instanceName = null;
                return false;
            }
        }
    private void TryToInitializeCounters()
    {
        if (!countersInitialized)
        {
            PerformanceCounterCategory category = new PerformanceCounterCategory(".NET CLR Networking 4.0.0.0");

            var instanceNames = category.GetInstanceNames().Where(i => i.Contains(string.Format("p{0}", pid)));

            if (instanceNames.Any())
            {
                bytesSentPerformanceCounter = new PerformanceCounter();
                bytesSentPerformanceCounter.CategoryName = ".NET CLR Networking 4.0.0.0";
                bytesSentPerformanceCounter.CounterName = "Bytes Sent";
                bytesSentPerformanceCounter.InstanceName = instanceNames.First();
                bytesSentPerformanceCounter.ReadOnly = true;

                bytesReceivedPerformanceCounter = new PerformanceCounter();
                bytesReceivedPerformanceCounter.CategoryName = ".NET CLR Networking 4.0.0.0";
                bytesReceivedPerformanceCounter.CounterName = "Bytes Received";
                bytesReceivedPerformanceCounter.InstanceName = instanceNames.First();
                bytesReceivedPerformanceCounter.ReadOnly = true;

                countersInitialized = true;
            }
        }
    }
예제 #4
0
        // Constructor
        public FrmMain()
        {
            InitializeComponent();
            InitializeXNA();

            // Load any images
            CursorTexture = new ParticleTexture("Cursor.png", Device);

            // Initialize data
            GameTimer = new PerformanceCounter();
            Emitters = new List<ParticleEmitter>();

            ToolEmitter = new FrmEmitter();
            ToolEmitter.Owner = this;

            // Create the Emitter Tool
            Point CenterScreen = new Point(Screen.PrimaryScreen.Bounds.Width >> 1, Screen.PrimaryScreen.Bounds.Height >> 1);

            Left = CenterScreen.X - (Width >> 1) - (ToolEmitter.Width >> 1) - 2;
            Top = CenterScreen.Y - (Height >> 1);
            ToolEmitter.Left = Right + 2;
            ToolEmitter.Top = CenterScreen.Y - (ToolEmitter.Height >> 1);

            ToolEmitter.Show();
        }
예제 #5
0
        // Logic Methods
        public void Update(PerformanceCounter GameTimer, Vector2 Gravity, float GravitationalPull)
        {
            // Update Color
            Vector4 NewColor = Overlay.ToVector4();
            NewColor.X += RedDelta * GameTimer.ElapsedTime;
            NewColor.Y += GreenDelta * GameTimer.ElapsedTime;
            NewColor.Z += BlueDelta * GameTimer.ElapsedTime;
            NewColor.W += AlphaDelta * GameTimer.ElapsedTime;
            Overlay = new Color(NewColor);

            // Update Velocity
            Velocity.X += VelocityDelta.X * GameTimer.ElapsedTime;
            Velocity.Y += VelocityDelta.Y * GameTimer.ElapsedTime;

            Vector2 DeltaPosWell = Gravity - Position;
            DeltaPosWell.Normalize();
            DeltaPosWell = DeltaPosWell * (GravitationalPull * GameTimer.ElapsedTime);
            Velocity = Velocity + DeltaPosWell;

            // Update Position
            Position = Position + (Velocity * GameTimer.ElapsedTime) ;

            // Update Scale and Velocity
            Scale += ScaleDelta * GameTimer.ElapsedTime;
            Rotation += RotationDelta * GameTimer.ElapsedTime;

            // Update the current life span
            CurrentLife += GameTimer.ElapsedTime;
        }
예제 #6
0
 /// <summary>
 /// Return total avaliable memory in MBs
 /// </summary>
 /// <returns></returns>
 public static long GetAvaliableMemory()
 {
     PerformanceCounter memoryAvaliable =
         new PerformanceCounter("Memory", "Available Bytes");
     long availableMemory = Convert.ToInt64(memoryAvaliable.NextValue()) / (1024 * 1024);
     return availableMemory;
 }
예제 #7
0
    private static void CreateCounters()
    {
        // Create the counter.
        PC = new PerformanceCounter("ElapsedTimeSampleCategory",
            "ElapsedTimeSample",
            false);

    }
예제 #8
0
 /// <summary>
 /// Return total CPU usage in %
 /// </summary>
 /// <param name="lDelay">Delay in seconds for more precision</param>
 /// <returns></returns>
 public static float GetCPUTotalUse(int lDelay = 1)
 {
     PerformanceCounter processorTotal =
         new PerformanceCounter("Processor", "% Processor Time", "_Total");
     processorTotal.NextValue();
     Thread.Sleep(lDelay * 1000);
     return processorTotal.NextValue();
 }
예제 #9
0
    public ThreadSendInfo()
    {
        cpuCounter = new PerformanceCounter();

        cpuCounter.CategoryName = "Processor";
        cpuCounter.CounterName = "% Processor Time";
        cpuCounter.InstanceName = "_Total";
        ramCounter = new PerformanceCounter("Memory", "Available MBytes");
    }
예제 #10
0
 /// <summary>
 /// Constructor.
 /// </summary>
 public DebugScreen(String name)
 {
     HumanReadableName = name;
     IsPopup = true;
     TransitionOnTime = TimeSpan.FromSeconds(0.5);
     TransitionOffTime = TimeSpan.FromSeconds(0.5);
     cpuCounter = new PerformanceCounter();
     cpuCounter.CategoryName = "Processor";
     cpuCounter.CounterName = "% Processor Time";
     cpuCounter.InstanceName = "_Total";
     ramCounter = new PerformanceCounter("Memory", "Available MBytes");
 }
예제 #11
0
        public string GetResponseText(WebRequest request, out string subsequentRequestsUrl)
        {
            // Requests to the Nest API result in a 307 redirect. The Nest documentation states that subsequent
            // requests should go to this redirected URL, so we capture this and return it in the out
            // variable for this method.
            //
            // For more information see the relevant section in https://developer.nest.com/documentation/data-rate-limits.

            var responseText = string.Empty;

            PerformanceCounter counter = null;

            if (_log.IsInfoEnabled)
            {
                counter = new PerformanceCounter();
                counter.Start();
            }

            try
            {
                var response = GetResponseWithBetterErrors(request);

                // The underlying call to GetResponse will have handled any 307 redirect, and the URL we were redirected to
                // (which must be used for subsequent requests) will be in the ResponseUri.AbsoluteUri.
                subsequentRequestsUrl = response.ResponseUri.AbsoluteUri;

                using (var responseStream = response.GetResponseStream())
                {
                    if (responseStream != null)
                    {
                        using (var reader = new StreamReader(responseStream))
                        {
                            responseText = reader.ReadToEnd();
                        }
                    }
                    else if (_log.IsWarnEnabled)
                    {
                        _log.WarnFormat("Null response received from '{0}'.", request.RequestUri.AbsoluteUri);
                    }
                }
            }
            finally
            {
                if (_log.IsInfoEnabled && counter != null)
                {
                    counter.Stop();
                    _log.InfoFormat("Received response in {0:0.00} seconds from {1} '{2}'.", counter.Duration.TotalSeconds, request.Method, request.RequestUri);
                }
            }

            return responseText;
        }
    public static int TestExport(String counterGroup, String counterSet, int value)
    {
        System.Console.Out.WriteLine(String.Format("Setting counter {0} for group {1} with value {2}", counterSet, counterGroup, value));

        // get an instance of our perf counter
        PerformanceCounter counter = new PerformanceCounter();
        counter.CategoryName = counterGroup;
        counter.CounterName = counterSet;
        counter.ReadOnly = false;
        counter.RawValue = value;

        counter.Close();
        return 0;
    }
예제 #13
0
 public CounterDisplay(MainWindow win, string cat, string counter, string instance)
     : base(string.Format ("{0}/{1}", cat, counter))
 {
     w = win;
     HBox hbox = new HBox (false, 6);
     VBox vbox = new VBox (false, 6);
     hbox.PackStart (vbox, false, false, 4);
     Label l = new Label (string.Format ("Instance: {0}", instance));
     l.Xalign = 0;
     vbox.PackStart (l, false, false, 0);
     rawval = new Label ("");
     rawval.Xalign = 0;
     vbox.PackStart (rawval, false, false, 0);
     error = new Label ("");
     error.Xalign = 0;
     vbox.PackStart (error, false, false, 0);
     type = new Label ("");
     type.Xalign = 0;
     vbox.PackStart (type, false, false, 0);
     draw = new CounterDrawing ();
     hbox.PackEnd (draw, true, true, 4);
     Add (hbox);
     Button rem = new Button ("Remove");
     vbox.PackStart (rem, false, false, 0);
     rem.Clicked += delegate {
         w.RemoveCounter (this);
     };
     ShowAll ();
     try {
         if (instance == null)
             countero = new PerformanceCounter (cat, counter);
         else
             countero = new PerformanceCounter (cat, counter, instance);
         type.Text = countero.CounterType.ToString ();
         Update ();
         //Console.WriteLine ("{0}", countero.RawValue);
         //Console.WriteLine ("'{0}' '{1}' '{3}': {2}", cat, counter, countero.RawValue, instance);
     } catch (Exception e) {
         error.Text = e.Message;
         Console.WriteLine (e.StackTrace);
     }
 }
        public GCMetricsProfilerVisualiser(
            IAssetManagerProvider assetManagerProvider,
            I2DRenderUtilities renderUtilities)
        {
            _renderUtilities = renderUtilities;
            _defaultFont = assetManagerProvider.GetAssetManager().Get<FontAsset>("font.Default");

#if PLATFORM_WINDOWS || PLATFORM_MACOS || PLATFORM_LINUX
            string instanceName;
            if (TryGetInstanceName(Process.GetCurrentProcess(), out instanceName))
            {
                _gen0PerformanceCounter = new PerformanceCounter(".NET CLR Memory", "# Gen 0 Collections",
                    instanceName, true);
                _gen1PerformanceCounter = new PerformanceCounter(".NET CLR Memory", "# Gen 1 Collections",
                    instanceName, true);
                _gen2PerformanceCounter = new PerformanceCounter(".NET CLR Memory", "# Gen 2 Collections",
                    instanceName, true);
            }
#endif
        }
예제 #15
0
        private EntityGame(Game game, SpriteBatch spriteBatch)
        {
            Game = game;
            Game.Exiting += (sender, args) => Exit();

            SpriteBatch = spriteBatch;
            Assets.LoadConent(game);

            //Inject debug info into active state
            StateChanged += state => LastID = 1;
            StateChanged += state => _debugInfo = new DebugInfo(state, "DebugInfo");
            StateChanged += state => ActiveCamera = new Camera(state, "EntityEngineDefaultCamera");

            Log = new Log();

            //Start counters

            Process p = Process.GetCurrentProcess();
            _ramCounter = new PerformanceCounter("Process", "Working Set", p.ProcessName);
            _cpuCounter = new PerformanceCounter("Process", "% Processor Time", p.ProcessName);
        }
예제 #16
0
        static void Main(string[] args)
        {
            List <string> cpuMaxedOutMessages = new List <string>();

            cpuMaxedOutMessages.Add("WARNING: Your CPU is about to catch fire!");
            cpuMaxedOutMessages.Add("WARNING: Oh my god you should not run your CPU that hard");
            cpuMaxedOutMessages.Add("WARNING: Stop downloading it's maxing me out");
            cpuMaxedOutMessages.Add("WARNING: Your CPU is officially chasing squirrels");
            cpuMaxedOutMessages.Add("RED ALERT! RED ALERT! RED ALERT! RED ALERT! RED ALERT!");

            Random rand = new Random();

            JerrySpeak("Welcolme to Jarvis version 1 point oh!", VoiceGender.Male);

            PerformanceCounter perfCPUCounter = new PerformanceCounter("Processor Information", "% Processor Time", "_Total");

            perfCPUCounter.NextValue();

            PerformanceCounter perfMemCounter = new PerformanceCounter("Memory", "Available MBytes");

            perfMemCounter.NextValue();

            PerformanceCounter perfUpTimeCounter = new PerformanceCounter("System", "System Up Time");

            perfUpTimeCounter.NextValue();

            TimeSpan upTimeSpan          = TimeSpan.FromSeconds(perfUpTimeCounter.NextValue());
            string   systemUpTimeMessage = string.Format("The current system up time is {0} Days {1} Hours {2} Minutes {3} Seconds",
                                                         (int)upTimeSpan.TotalDays,
                                                         (int)upTimeSpan.Hours,
                                                         (int)upTimeSpan.Minutes,
                                                         (int)upTimeSpan.Seconds
                                                         );

            JerrySpeak(systemUpTimeMessage, VoiceGender.Male, 5);

            int speechSpeed = 1;

            bool isChromeOpenedAlready = false;

            while (true)
            {
                int currentCPUPercentage   = (int)perfCPUCounter.NextValue();
                int currentAvailableMemory = (int)perfMemCounter.NextValue();

                Console.WriteLine("CPU Load:         {0}%", currentCPUPercentage);
                Console.WriteLine("Available Memory: {0}MB", currentAvailableMemory);

                if (currentCPUPercentage > 80)
                {
                    if (currentCPUPercentage == 100)
                    {
                        if (speechSpeed < 5)
                        {
                            speechSpeed++;
                        }

                        string cpuLoadVocalMessage = cpuMaxedOutMessages[rand.Next(5)];

                        if (isChromeOpenedAlready == false)
                        {
                            openWebSite("https://www.facebook.com/");
                            isChromeOpenedAlready = true;
                        }

                        JerrySpeak(cpuLoadVocalMessage, VoiceGender.Female, speechSpeed);
                    }
                    else
                    {
                        string cpuLoadVocalMessage = string.Format("The current CPU Load is {0} percent", currentCPUPercentage);
                        JerrySpeak(cpuLoadVocalMessage, VoiceGender.Female, 5);
                    }
                }

                if (currentAvailableMemory < 1024)
                {
                    string memAvailableVocalMessage = string.Format("You currently have {0} Megabytes of memory available", currentAvailableMemory);
                    JerrySpeak(memAvailableVocalMessage, VoiceGender.Male, 10);
                }

                Thread.Sleep(1000);
            }
        }
예제 #17
0
    private void RefreshServerInfo(List<string> recPaths)
    {
        string manufacturer = "";
          string model = "";
          string computername = "";
          UInt64 totalPhysicalMem = 0;

          ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT model,manufacturer,name,totalPhysicalMemory FROM Win32_ComputerSystem");
          ManagementObjectCollection queryCollection = query.Get();
          foreach (ManagementObject mo in queryCollection)
          {
        model = mo["model"].ToString();
        manufacturer = mo["manufacturer"].ToString();
        computername = mo["name"].ToString();
        totalPhysicalMem = Convert.ToUInt64(mo["totalphysicalmemory"]);
        totalPhysicalMem = (totalPhysicalMem / 1024) / 1024;
          }

          lMachinename.Text = computername + " (" + manufacturer + " - " + model + ")";
          lOS.Text = GetOSVersionStr();

          float cpuUsage=cpuCounter.NextValue();
          if (cpuUsage == 0)
          {
        System.Threading.Thread.Sleep(1000);
        cpuUsage = cpuCounter.NextValue();
          }

          lCPU.Text = Convert.ToInt32(cpuUsage).ToString() + " %";

          PerformanceCounter ramCounter = new PerformanceCounter("Memory", "Available MBytes");
          lMemory.Text = ramCounter.NextValue() + " Mb / "+totalPhysicalMem.ToString()+ "Mb";

          string usages="";
          foreach (string drive in recPaths) {
        if(drive.Length > 0)
          usages += GetDriveUsageStr(drive.Substring(0, 2)) + "<br/>";
          }
          lSpace.Text=usages;
    }
예제 #18
0
        private static async Task MainAsync(string[] args, CancellationToken cancel)
        {
            Console.CursorVisible        = false;
            Console.TreatControlCAsInput = true;
            try
            {
                CancellationTokenSource cts = null;
                Task burner = null;

                const int CAPACITY = 4 * 2;
                var       history  = new Queue <Datum>(CAPACITY);

                var options = new FdbConnectionOptions
                {
                    ClusterFile    = Program.ClusterPath,
                    DefaultTimeout = TimeSpan.FromSeconds(10)
                };
                //TODO: proper parsing of command line arguments!

                using (var db = await Fdb.OpenAsync(options, cancel))
                {
                    bool exit    = false;
                    bool hot     = false;
                    bool repaint = true;

                    var processName       = Process.GetCurrentProcess().ProcessName;
                    var perCpu            = new PerformanceCounter("Process", "% Processor Time", processName);
                    var perfDiskReads     = new PerformanceCounter("PhysicalDisk", "Disk Read Bytes/sec", "0 C:");
                    var perfDiskWrites    = new PerformanceCounter("PhysicalDisk", "Disk Write Bytes/sec", "0 C:");
                    var perfDiskWriteIops = new PerformanceCounter("PhysicalDisk", "Disk Writes/sec", "0 C:");
                    var perfDiskReadIops  = new PerformanceCounter("PhysicalDisk", "Disk Reads/sec", "0 C:");

                    const int COL0 = 1;
                    const int COL1 = COL0 + 15;
                    const int COL2 = COL1 + 15;
                    const int COL3 = COL2 + 15;
                    const int COL4 = COL3 + 15;

                    while (!exit && !cancel.IsCancellationRequested)
                    {
                        if (Console.KeyAvailable)
                        {
                            var k = Console.ReadKey();
                            switch (k.Key)
                            {
                            case ConsoleKey.Escape:
                            {                                     // [ESC]
                                exit = true;
                                break;
                            }

                            case ConsoleKey.C:
                            {
                                if (k.Modifiers.HasFlag(ConsoleModifiers.Control))
                                {                                         // CTRL-C
                                    exit = true;
                                }
                                break;
                            }

                            case ConsoleKey.R:
                            {
                                Randomized = !Randomized;
                                repaint    = true;
                                break;
                            }

                            case ConsoleKey.V:
                            {                                     // Change Value Size
                                CurrentSize = (CurrentSize + 1) % VALUE_SIZES.Length;
                                Value       = Slice.Random(Rnd, VALUE_SIZES[CurrentSize]);
                                repaint     = true;
                                break;
                            }

                            case ConsoleKey.Spacebar:
                            {
                                hot     = !hot;
                                repaint = true;
                                if (hot)
                                {
                                    cts    = new CancellationTokenSource();
                                    burner = Task.Run(() => BurnerThread(db, cts.Token), cts.Token);
                                }
                                else
                                {
                                    cts.Cancel();
                                    try { await burner; }
                                    catch (TaskCanceledException) { }
                                    cts.Dispose();
                                }
                                break;
                            }
                            }
                        }

                        if (!repaint)
                        {
                            await Task.Delay(250);
                        }

                        long   curKeys        = Volatile.Read(ref Keys);
                        long   curTrans       = Volatile.Read(ref Transactions);
                        long   curBytes       = Volatile.Read(ref Bytes);
                        double curDiskWrites  = perfDiskWrites.NextValue();
                        double curDiskReads   = perfDiskReads.NextValue();
                        double curDiskWriteIo = perfDiskWriteIops.NextValue();
                        double curDiskReadIo  = perfDiskReadIops.NextValue();

                        while (history.Count >= CAPACITY)
                        {
                            history.Dequeue();
                        }

                        var now = DateTime.UtcNow;
                        history.Enqueue(new Datum
                        {
                            Date          = now,
                            Keys          = curKeys,
                            Commits       = curTrans,
                            Bytes         = curBytes,
                            DiskWriteBps  = curDiskWrites,
                            DiskReadBps   = curDiskReads,
                            DiskWriteIops = curDiskWriteIo,
                            DiskReadIops  = curDiskReadIo,
                        });

                        if (repaint)
                        {
                            Console.Title = "FdbBurner - " + (!hot ? "ICY COLD" : Randomized ? "HOT HOT HOT" : "HOT HOT");

                            Console.BackgroundColor = !hot ? ConsoleColor.DarkCyan : Randomized ? ConsoleColor.DarkRed : ConsoleColor.DarkGreen;
                            Console.Clear();
                            Console.ForegroundColor = ConsoleColor.Gray;
                            WriteAt(COL0, 1, "Pattern   : {0,10}", "");
                            WriteAt(COL2, 1, "Value Size: {0,6} bytes", "");
                            WriteAt(COL0, 3, "{0,-12}", "Transactions");
                            WriteAt(COL1, 3, "{0,-12}", "Keys");
                            WriteAt(COL2, 3, "{0,-10}", "Written Bytes");
                            WriteAt(COL3, 3, "{0,-10}", "Disk Writes");
                            WriteAt(COL4, 3, "{0,-10}", "Disk Reads");
                            WriteAt(COL3, 7, "{0,-10}", "Write IOPS");
                            WriteAt(COL4, 7, "{0,-10}", "Read IOPS");

                            repaint = false;
                        }

                        Console.ForegroundColor = ConsoleColor.White;
                        WriteAt(COL0 + 12, 1, "{0,-10}", Randomized ? "Random" : "Sequential");
                        WriteAt(COL2 + 12, 1, "{0,6:N0}", Value.Count);

                        WriteAt(COL0, 4, "{0,12:N0}", curTrans);
                        WriteAt(COL1, 4, "{0,12:N0}", curKeys);
                        WriteAt(COL2, 4, "{0,10:N1} MB", curBytes / 1048576.0);
                        WriteAt(COL3, 4, "{0,10:N1} MB/s", curDiskWrites / 1048576.0);
                        WriteAt(COL4, 4, "{0,10:N1} MB/s", curDiskReads / 1048576.0);

                        if (history.Count > 1)
                        {
                            var    old = history.Peek();
                            var    dur = (now - old.Date).TotalSeconds;
                            double speed;

                            Console.ForegroundColor = ConsoleColor.White;

                            speed = (curTrans - old.Commits) / dur;
                            WriteAt(COL0, 5, "{0,12:N0}", speed);

                            speed = (curKeys - old.Keys) / dur;
                            WriteAt(COL1, 5, "{0,12:N0}", speed);

                            speed = (curBytes - old.Bytes) / dur;
                            WriteAt(COL2, 5, "{0,10:N1} MB/s", speed / 1048576.0);

                            var writeSpeed = history.Average(d => d.DiskWriteBps);
                            var readSpeed  = history.Average(d => d.DiskReadBps);
                            WriteAt(COL3, 5, "{0,10:N1} MB/s", writeSpeed / 1048576.0);
                            WriteAt(COL4, 5, "{0,10:N1} MB/s", readSpeed / 1048576.0);

                            var writeIops = history.Average(d => d.DiskWriteIops);
                            var readIops  = history.Average(d => d.DiskReadIops);
                            WriteAt(COL3, 8, "{0,10:N0} iops", writeIops);
                            WriteAt(COL4, 8, "{0,10:N0} iops", readIops);

                            var factor = speed > 0 ? writeSpeed / speed : 0;
                            WriteLarge(0, 16, "{0,8:F3}", speed / 1048576.0);
                            WriteLarge(0, 24, "{0,8:F3}", writeSpeed / 1048576.0);
                            WriteLarge(0, 32, "X{0,5:F1}", factor);
                        }


                        Console.SetCursorPosition(0, 0);
                    }
                }
            }
            finally
            {
                Console.CursorVisible = true;
                Console.ResetColor();
                Console.Clear();
            }
        }
예제 #19
0
 public HddMetricJob(IHddMetricsRepository repository, ILogger <HddMetricJob> logger)
 {
     _repository = repository;
     _logger     = logger;
     _hddCounter = new PerformanceCounter("Логический диск", "% свободного места", "F:");
 }
예제 #20
0
		/// <summary>
		/// Gets the result of the specified performance counter .
		/// </summary>
		/// <param name="pc">The PerformanceCounter.</param>
		/// <returns></returns>
		public PerformanceResult GetPerformanceCounterResult(PerformanceCounter pc)
		{
			var pco = m_Stopwatches[(int)pc];
			return (pco != null) ? pco.GetResult() : null;
		}
예제 #21
0
        static void Main(string[] args)
        {
            // Note : with Console.WriteLine can either use string.Format or just omit it - result is the same

            Console.WriteLine(string.Format("{0}", "Left Justified Text Is Default"));
            Console.WriteLine();

            Console.WriteLine(string.Format("{0,50}", "Positive Number Right Justifies"));
            Console.WriteLine(string.Format("{0,50}", "Right Here"));

            Console.WriteLine();
            Console.WriteLine(string.Format("{0,-14}", "Negative Number Left Justifies"));
            Console.WriteLine(string.Format("{0,-14}", "y"));


            Console.WriteLine();
            Console.WriteLine(string.Format("{0,40}", "Right Justified Year"));
            Console.WriteLine(string.Format("{0,40:yyyy}", DateTime.Now));
            Console.WriteLine(string.Format("{0,40}", "Right Justified Month"));
            Console.WriteLine(string.Format("{0,40:MMM}", DateTime.Now));
            Console.WriteLine(string.Format("{0,40}", "Right Justified Day"));
            Console.WriteLine(string.Format("{0,40:dd}", DateTime.Now));

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine(string.Format("{0,30}", 123.456));
            Console.WriteLine(string.Format("{0,-30}", "N0 removes decimals"));
            Console.WriteLine(string.Format("{0,30:N0}", 123.456));
            Console.WriteLine(string.Format("{0,-30}", "N1 one number after decimal"));
            Console.WriteLine(string.Format("{0,30:N1}", 123.456));
            Console.WriteLine(string.Format("{0,-30}", "N6 six decimal places"));
            Console.WriteLine(string.Format("{0,30:N6}", 123.456));


            Console.WriteLine(string.Format("{0,-30}", "Pad out with zeros using :000000.0000"));
            Console.WriteLine(string.Format("{0,30:000000.0000}", 123.456));


            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine(string.Format("{0,35}", "0.123456"));
            Console.WriteLine(string.Format("{0,-35}", "P2 = Percentage to 2DP"));
            Console.WriteLine(string.Format("{0,35:P2}", 0.123456));
            Console.WriteLine(string.Format("{0,-35}", "P4 = Percentage to 4DP"));
            Console.WriteLine(string.Format("{0,35:P4}", 0.123456));


            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("Output number to fixed decimal places");
            Console.WriteLine("{0:000.000}", 5);         //  005.000
            Console.WriteLine("{0:000.000}", 1234.5678); //  1234.568 ie rounding up the third decimal place


            // display exponential as a long
            PerformanceCounter PC = new PerformanceCounter();

            PC.CategoryName = "Process";
            PC.CounterName  = "Private Bytes";
            PC.InstanceName = "Explorer";
            Console.WriteLine(PC.NextValue());               // exponential
            Console.WriteLine(PC.NextValue().ToString());    // exponential
            Console.WriteLine(PC.NextValue().ToString("0")); // force as long



            string s = System.String.Format("It is now {0:d} at {0:t}", DateTime.Now);

            Console.WriteLine(s);
            // Output similar to: 'It is now 4/10/2015 at 10:04 AM'

            string[]  names = { "Adam",    "Bridgette", "Carla", "Daniel",
                                "Ebenezer", "Francine",  "George" };
            decimal[] hours = { 40, 6.667m, 40.39m, 82, 40.333m, 80,
                                16.75m };

            Console.WriteLine("{0,-20} {1,5}\n", "Name", "Hours");
            for (int i = 0; i < names.Length; i++)
            {
                Console.WriteLine("{0,-20} {1,5:N1}", names[i], hours[i]);
            }

            // The example displays the following output:
            //       Name                 Hours
            //
            //       Adam                  40.0
            //       Bridgette              6.7
            //       Carla                 40.4
            //       Daniel                82.0
            //       Ebenezer              40.3
            //       Francine              80.0
            //       George                16.8


            Console.ReadLine();
        }
예제 #22
0
        static void Main(string[] args)
        {
            ///Challenge 1

            //try
            //{
            //    var zero = 0;
            //    var result = 1 / zero;
            //}
            //catch (DivideByZeroException ex)
            //{
            //    string sourceName = "Sample Log - Challenge_Cap_15";
            //    string logName = "Challenge_Cap_15";
            //    string machineName = ".";// . means local machine
            //    string entryTowritten = ex.Message;
            //    if (!EventLog.SourceExists(sourceName, machineName))
            //    {
            //        EventLog.CreateEventSource(sourceName, logName);
            //    }
            //    EventLog.WriteEntry(
            //        sourceName, entryTowritten, EventLogEntryType.Information
            //        );
            //}


            //Challenge 2
            //Create a counter
            if (!PerformanceCounterCategory.Exists(CategoryName))
            {
                CounterCreationDataCollection counters       = new CounterCreationDataCollection();
                CounterCreationData           totalOfNothing = new CounterCreationData();
                totalOfNothing.CounterName = CounterName;
                totalOfNothing.CounterHelp = "Counter of nothing kkk";
                totalOfNothing.CounterType = PerformanceCounterType.NumberOfItems32;
                counters.Add(totalOfNothing);
#pragma warning disable CS0618 // O tipo ou membro é obsoleto
                PerformanceCounterCategory.Create(CategoryName, "Ajuda", counters);
#pragma warning restore CS0618 // O tipo ou membro é obsoleto
                Console.WriteLine("Performance Counter Created.");
            }
            else
            {
                Console.WriteLine("Performance Counter already Created.");
            }

            PerformanceCounter successfullCounter = new PerformanceCounter();
            successfullCounter.CategoryName = CategoryName;
            successfullCounter.CounterName  = CounterName;
            successfullCounter.MachineName  = ".";
            successfullCounter.ReadOnly     = false;

            var exit  = false;
            var input = 0;

            do
            {
                Console.WriteLine("1-Input Increment");
                Console.WriteLine("2-Input Decrement");
                Console.WriteLine("3-Output");
                Console.WriteLine("4-Exit");
                var a = Console.ReadLine();
                switch (a)
                {
                case "1":
                    successfullCounter.IncrementBy(100);
                    break;

                case "2":
                    for (int i = 0; i < 100; i++)
                    {
                        successfullCounter.Decrement();
                    }
                    break;

                case "3":
                    Console.WriteLine(successfullCounter.RawValue);
                    break;

                case "4":
                    exit = true;
                    break;

                default:
                    Console.WriteLine("Oh noo! it's wrong!");
                    break;
                }
            } while (!exit);
        }
예제 #23
0
 public ProfileHandler()
 {
     _cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
     _ramCounter = new PerformanceCounter("Memory", "Available MBytes");
 }
예제 #24
0
        bool StartProbe(bool writeEvent)
        {
            try
            {
                if (_perfCounter != null)
                {
                    _perfCounter.Dispose();
                    _perfCounter = null;
                }

                if (!String.IsNullOrEmpty(InstanceName))
                {
                    if (!PerformanceCounterCategory.Exists(CategoryName))
                    {
                        PerformanceCounter.CloseSharedResources();
                        TraceEvent(TraceEventType.Critical, float.NaN, "Category Name " + CategoryName + " is not available.");
                        return(false);
                    }

                    PerformanceCounterCategory cat = new PerformanceCounterCategory(CategoryName);
                    string[] instances             = cat.GetInstanceNames();
                    foreach (string instance in instances)
                    {
                        if (instance.IndexOf(InstanceName, StringComparison.CurrentCultureIgnoreCase) != -1)
                        {
                            if (_perfCounter == null || _perfCounter.InstanceName.Equals(InstanceName, StringComparison.CurrentCultureIgnoreCase))
                            {
                                _perfCounter = new PerformanceCounter(CategoryName, CounterName, instance, true);
                            }
                        }
                    }
                    if (_perfCounter == null)
                    {
                        // Check if it is okay that instance cannot be found
                        if (DefaultValue.HasValue && writeEvent)
                        {
                            TraceEvent(TraceEventType.Information, DefaultValue.Value, "Instance does not exist");
                            return(false);
                        }
                        _perfCounter = new PerformanceCounter(CategoryName, CounterName, InstanceName, true);
                    }
                }
                else
                if (!String.IsNullOrEmpty(ServiceName))
                {
                    // Lookup the process instance name using the ServiceName
                    uint processId = GetProcessIDByServiceName(ServiceName);
                    if (processId == 0)
                    {
                        if (DefaultValue.HasValue && writeEvent)
                        {
                            TraceEvent(TraceEventType.Information, DefaultValue.Value, "Service '" + ServiceName + "' is not running");
                            return(false);
                        }
                        else
                        {
                            throw new InvalidOperationException("Service '" + ServiceName + "' is not running");
                        }
                    }

                    string instanceName = GetProcessInstanceName((long)processId);
                    if (instanceName == null)
                    {
                        throw new InvalidOperationException("Service instance '" + ServiceName + "' cannot be found");
                    }
                    _perfCounter = new PerformanceCounter(CategoryName, CounterName, instanceName, true);
                }
                else
                {
                    _perfCounter = new PerformanceCounter(CategoryName, CounterName, true);
                }

                _prevSample = _perfCounter.NextSample();
                return(true);
            }
            catch (Exception)
            {
                if (_perfCounter != null)
                {
                    _perfCounter.Dispose();
                    _perfCounter = null;
                }
                PerformanceCounter.CloseSharedResources();
                throw;
            }
        }
 internal PerformanceCounterInfo(string name, PerformanceCounter performanceCounters)
     : this(name, performanceCounters, null, null, null, null, null)
 {
 }
예제 #26
0
 public PALMachineInfo()
 {
     m_CPUCounter          = new PerformanceCounter("Processor", "% Processor Time", "_Total", true);
     m_RAMAvailableCounter = new PerformanceCounter("Memory", "Available MBytes", true);
     m_IsMono = Type.GetType("Mono.Runtime") != null;
 }
 private void LogPerformanceCounterData(PerformanceCounter memoryMonitor, PerformanceCounter processorMonitor)
 {
     LogMessage(string.Format("\t\tMemory Usage:\t{0,15:N0}", memoryMonitor.NextSample().RawValue));
     LogMessage(string.Format("\t\tProcessor Usage:{0,15:N0}", processorMonitor.NextSample().RawValue));
 }
        internal int Run()
        {
            string thisProcessName = Process.GetCurrentProcess().ProcessName;

            using (PerformanceCounter memoryMonitor = new PerformanceCounter("Process", "Working Set", thisProcessName))
            {
                memoryMonitor.NextSample();
                using (PerformanceCounter processorMonitor = new PerformanceCounter("Process", "% Processor Time", thisProcessName))
                {
                    processorMonitor.NextSample();
                    networkGeneratorLog = new List <string>();
                    LogMessage("********************************************************");
                    LogMessage(string.Format("{0,25}\t{1:G}", "Start Network Generation:", DateTime.Now));
                    LogMessage(string.Format("{0,25}\t{1:N0}\tEdges: {2:N0}", "Requested Nodes:", this.networkNodeCount, this.networkEdgeCount));
                    LogMessage(string.Format("{0,25}\t{1:N0}\tEdges: {2:N0}", "Start Ids - Nodes:", this.nodeIdStartValue, this.edgeIDStartValue));
                    ChirperGraphMLDocument graphDoc = new ChirperGraphMLDocument();
                    LogMessage(string.Empty);
                    LogMessage("Starting node generation...");

                    TimeSpan nodeGenerationTime = GenerateChirperUserNodes(graphDoc);
                    LogMessage("\tNode generation complete in " + nodeGenerationTime);
                    LogPerformanceCounterData(memoryMonitor, processorMonitor);

                    LogMessage(string.Empty);
                    FlushLog();

                    int      duplicateEdgeStatistic = 0;
                    TimeSpan edgeGenerationTime     = default(TimeSpan);
                    if (this.networkEdgeCount > 0)
                    {
                        LogMessage("Starting edge generation...");
                        edgeGenerationTime = GenerateChirperFollowerEdge(graphDoc, ref duplicateEdgeStatistic);

                        LogMessage("\tEdge generation complete in " + edgeGenerationTime);
                        LogMessage("\tDuplicates generated: " + duplicateEdgeStatistic);
                        LogPerformanceCounterData(memoryMonitor, processorMonitor);
                        LogMessage(string.Empty);
                    }
                    else
                    {
                        LogMessage("Edge generation suppressed from command line.");
                        LogMessage(string.Empty);
                    }

                    Stopwatch stopwatch = new Stopwatch();
                    FlushLog();

                    LogMessage("Starting GraphML File write...");
                    stopwatch.Restart();
                    graphDoc.WriteXmlWithWriter(this.graphMLFile);
                    stopwatch.Stop();
                    TimeSpan xmlWriteTime = TimeSpan.FromSeconds(stopwatch.Elapsed.TotalSeconds);
                    LogMessage("\tGraphML file write complete in " + xmlWriteTime);
                    LogPerformanceCounterData(memoryMonitor, processorMonitor);

                    LogMessage(string.Empty);
                    LogMessage(string.Format(CultureInfo.InvariantCulture, "{0,30}\t{1}", "Total Graph Generation Time:", (nodeGenerationTime + edgeGenerationTime + xmlWriteTime)));
                    LogMessage(string.Empty);
                    FlushLog();

                    // Get the size of the file so we can add the statistic.
                    FileInfo fileInfo = new FileInfo(this.graphMLFile);
                    fileInfo.Refresh();
                    long   fileLength = fileInfo.Length;
                    string range      = "bytes";
                    if (fileLength > Kilo)
                    {
                        fileLength = fileLength / Kilo;
                        range      = "KB";
                    }
                    if (fileLength > Kilo)
                    {
                        fileLength = fileLength / Kilo;
                        range      = "MB";
                    }

                    LogMessage(string.Format(CultureInfo.InvariantCulture, "{0,30}\t{1:N0} {2}", "GraphML File Size:", fileLength, range));

                    LogMessage(string.Empty);
                    FlushLog();
                }
            }

            // Using Linq to XML here to insert the statistic comment won't adversely affect performance.
            //XComment statisticsComment = new XComment(summaryMessageStringBuilder.ToString());
            //XDocument generatedGraphMLDoc = XDocument.Load(graphMLFile);
            //XElement graphElement = generatedGraphMLDoc.Root;
            //graphElement.AddFirst(statisticsComment);
            //graphElement.Document.Save(this.graphMLFile);

            return(0);
        }
예제 #29
0
        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or
        /// resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            if (_printThread != null)
            {
                NCacheLog.Flush();
#if !NETCORE
                _printThread.Abort();
#else
                _printThread.Interrupt();
#endif
            }
            _printThread = null;
            if (_logger != null)
            {
                _logger.Close();
            }

            lock (this)
            {
                if (_pcBcastQueueCount != null)
                {
                    _pcBcastQueueCount.RemoveInstance();
                    _pcBcastQueueCount.Dispose();
                    _pcBcastQueueCount = null;
                }
                if (_pcMcastQueueCount != null)
                {
                    _pcMcastQueueCount.RemoveInstance();
                    _pcMcastQueueCount.Dispose();
                    _pcMcastQueueCount = null;
                }
                if (_pcTcpDownQueueCount != null)
                {
                    _pcTcpDownQueueCount.RemoveInstance();
                    _pcTcpDownQueueCount.Dispose();
                    _pcTcpDownQueueCount = null;
                }
                if (_pcTcpUpQueueCount != null)
                {
                    _pcTcpUpQueueCount.RemoveInstance();
                    _pcTcpUpQueueCount.Dispose();
                    _pcTcpUpQueueCount = null;
                }
                if (_pcClusteredOperationsPerSec != null)
                {
                    _pcClusteredOperationsPerSec.RemoveInstance();
                    _pcClusteredOperationsPerSec.Dispose();
                    _pcClusteredOperationsPerSec = null;
                }
                if (_pcBytesSentPerSec != null)
                {
                    _pcBytesSentPerSec.RemoveInstance();
                    _pcBytesSentPerSec.Dispose();
                    _pcBytesSentPerSec = null;
                }
                if (_pcBytesReceivedPerSec != null)
                {
                    _pcBytesReceivedPerSec.RemoveInstance();
                    _pcBytesReceivedPerSec.Dispose();
                    _pcBytesReceivedPerSec = null;
                }
                if (_pcSocketSendSize != null)
                {
                    _pcSocketSendSize.RemoveInstance();
                    _pcSocketSendSize.Dispose();
                    _pcSocketSendSize = null;
                }
                if (_pcSocketSendTime != null)
                {
                    _pcSocketSendTime.RemoveInstance();
                    _pcSocketSendTime.Dispose();
                    _pcSocketSendTime = null;
                }
                if (_pcSocketReceiveSize != null)
                {
                    _pcSocketReceiveSize.RemoveInstance();
                    _pcSocketReceiveSize.Dispose();
                    _pcSocketReceiveSize = null;
                }
                if (_pcSocketReceiveTime != null)
                {
                    _pcSocketReceiveTime.RemoveInstance();
                    _pcSocketReceiveTime.Dispose();
                    _pcSocketReceiveTime = null;
                }


                ///
                if (_pcDispatchEnter != null)
                {
                    _pcDispatchEnter.RemoveInstance();
                    _pcDispatchEnter.Dispose();
                    _pcDispatchEnter = null;
                }

                if (_pcTcpDownEnter != null)
                {
                    _pcTcpDownEnter.RemoveInstance();
                    _pcTcpDownEnter.Dispose();
                    _pcTcpDownEnter = null;
                }

                if (_pcClusterOpsSent != null)
                {
                    _pcClusterOpsSent.RemoveInstance();
                    _pcClusterOpsSent.Dispose();
                    _pcClusterOpsSent = null;
                }

                if (_pcClusterOpsReceived != null)
                {
                    _pcClusterOpsReceived.RemoveInstance();
                    _pcClusterOpsReceived.Dispose();
                    _pcClusterOpsReceived = null;
                }

                if (_pcResponseSent != null)
                {
                    _pcResponseSent.RemoveInstance();
                    _pcResponseSent.Dispose();
                    _pcResponseSent = null;
                }


                ////
            }
        }
예제 #30
0
        private static Process FindPidFromIndexedProcessName(string indexedProcessName)
        {
            var parentId = new PerformanceCounter("Process", "Creating Process ID", indexedProcessName);

            return(Process.GetProcessById((int)parentId.NextValue()));
        }
예제 #31
0
 public void Close()
 {
     if (_pcs != null)
     {
         _pcs.RemoveInstance();
         _pcs.Close();
         _pcs = null;
     }
 }
예제 #32
0
        static void Main(string[] args)

        {
            Console.Title = "Server Monitor";
            string path = @"C:\Logs\Server_Monitor.csv";

            Console.WriteLine("Generando Server_Monitor.csv\nEspere 10 segundos hasta que se complete.\nSi tiene el documento Server_Monitor.csv porfavor cerrarlo\nEl archivo se generara en " + path);
            Console.Beep();


            #region Definitions
            //Ram pc
            PerformanceCounter pcRAM = new PerformanceCounter();
            pcRAM.CategoryName = "Memory";
            //pcRAM.CounterName = "% Committed Bytes in Use";
            pcRAM.CounterName = "Available Mbytes";
            pcRAM.NextValue();

            //cores pcs
            //multi core
            int coreCount = 0;
            foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_Processor").Get())
            {
                coreCount += int.Parse(item["NumberOfCores"].ToString());
            }

            PerformanceCounter[] pc = new PerformanceCounter[coreCount];

            for (int i = 0; i < coreCount; i++)
            {
                pc[i] = new PerformanceCounter("Processor", "% Processor Time", i.ToString());

                pc[i].NextValue();
            }
            //temp
            //PerformanceCounter pcTemp = new PerformanceCounter("Thermal Zone Information", "Temperature", @"\_TZ.TZ00");
            //pcTemp.NextValue();

            //general cpu
            PerformanceCounter pcCPU = new PerformanceCounter();
            pcCPU.CategoryName = "Processor";
            pcCPU.CounterName  = "% Processor Time";
            pcCPU.InstanceName = "_Total";
            pcCPU.NextValue();
            //Drives
            DriveInfo[] drives = DriveInfo.GetDrives();

            string[] driveInfo = new string[drives.Length];
            int      index     = 0;
            #endregion
            System.Threading.Thread.Sleep(5000); //Delay de 5 segundos
            #region Strings
            DateTime date = DateTime.Now;

            string datestring = $"Fecha y hora; { date.ToString() } ";


            string cpuUsageText = $"Uso de CPU total; {(int)pcCPU.NextValue()} % ";

            string ramUsageText = $"RAM disponible; {(int)pcRAM.NextValue()} MB ";

            //string cpuTemperature = $"Temperatura; {(int)(pcTemp.NextValue() - 273.15f)} \u00B0C";

            string[] cpuCoresUsagesText = new string[coreCount];

            for (int i = 0; i < coreCount; i++)
            {
                cpuCoresUsagesText[i] = $"Uso de CPU Core({i}); {(int)pc[i].NextValue()} %";
            }

            foreach (DriveInfo drive in drives)
            {
                driveInfo[index] = ($"Dispositivo {drive.Name}; Espacio Disponible " +
                                    $"{((drive.AvailableFreeSpace/1024)/1024)/1024} GB de {((drive.TotalSize/1024)/1024)/1024} GB");

                index++;
            }

            #endregion

            System.Threading.Thread.Sleep(5000); //Delay de 5 segundos

            // Create a file to write to.
            using (StreamWriter sw = File.CreateText(path))
            {
                sw.Write($"{datestring}\n{cpuUsageText}\n{string.Join("\n", cpuCoresUsagesText)}\n{ramUsageText}\nAlmacenamiento\n{string.Join("\n", driveInfo)}");
                //sw.WriteLine("");
                //sw.WriteLine("");
            }
        }
예제 #33
0
        public static void Main()
        {
            //Screen.BackgroundColor = ScreenColor.Green;
            //Screen.Color = ScreenColor.Red;
            //Screen.Clear();
            //Screen.Goto(0, 0);
            //Screen.Write('A');

            //Serial.SetupPort(Serial.COM1);
            //Serial.Write(Serial.COM1, "Hello");

            BootMemory.Setup();

            // Setup Kernel Log
            var kmsgHandler = new KernelMessageWriter();

            KernelMessage.SetHandler(kmsgHandler);
            KernelMessage.WriteLine("<LOADER:CONSOLE:BEGIN>");
            Assert.Setup(AssertError);
            PerformanceCounter.Setup();

            // Parse Boot Informations
            Multiboot.Setup();

            // Parse Kernel ELF section
            SetupOriginalKernelElf();

            // Print all section of Kernel ELF (for information only)
            DumpElfInfo();

            // Copy Section to a final destination
            SetupKernelSection();

            // Collection informations we need to pass to the kernel
            BootInfo_.Setup();

            // Setup Global Descriptor Table
            var map = BootMemory.AllocateMemoryMap(0x1000, BootInfoMemoryType.GDT, AddressSpaceKind.Both);

            BootInfo_.AddMap(map);
            GDT.Setup(map.Start);

            // Now we enable Paging. It's important that we do not cause a Page Fault Exception,
            // Because IDT is not setup yet, that could handle this kind of exception.

            PageTable.ConfigureType(BootInfo_.BootInfo->PageTableType);
            map = BootMemory.AllocateMemoryMap(PageTable.KernelTable.InitalMemoryAllocationSize, BootInfoMemoryType.PageTable, AddressSpaceKind.Both);
            BootInfo_.AddMap(map);
            PageTable.KernelTable.Setup(map.Start);
            MapMemory();
            PageTable.KernelTable.EnablePaging();

            // Because Kernel is compiled in virtual address space, we need to remap the pages
            MapKernelImage();

            // Get Entry Point of Kernel
            uint kernelEntry = GetKernelStartAddr();

            if (kernelEntry == 0)
            {
                KernelMessage.WriteLine("No kernel entry point found {0:X8}");
                KernelMessage.WriteLine("Is the name of entry point correct?");
                KernelMessage.WriteLine("Are symbols emitted?");
                KernelMessage.WriteLine("System halt!");
                while (true)
                {
                    Native.Nop();
                }
            }
            KernelMessage.WriteLine("Call Kernel Start at {0:X8}", kernelEntry);

            // Start Kernel.
            CallAddress(kernelEntry);

            // If we hit this code location, the Kernel Main method returned.
            // This would be a general fault. Normally, this code section will overwritten
            // by the kernel, so normally, it can never reach this code position.
            KernelMessage.WriteLine("Unexpected return from Kernel Start");

            Debug.Break();
        }
 public SystemMonitor()
 {
     cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
     cpuCounter.NextValue();
     ramCounter = new PerformanceCounter("Memory", "Available MBytes");
 }
 private void SetupPerformanceCounters(string instanceName)
 {
     m_CpuUsagePC    = new PerformanceCounter("Process", "% Processor Time", instanceName);
     m_ThreadCountPC = new PerformanceCounter("Process", "Thread Count", instanceName);
     m_WorkingSetPC  = new PerformanceCounter("Process", "Working Set", instanceName);
 }
예제 #36
0
 /// <summary>
 ///     Verified that the counter exists
 /// </summary>
 public void Initialize(PerformanceCounter cnt)
 {
     counter = cnt;
     timer   = new Timer(ClearPerfCounter, null, 0, 2000);
 }
 public static bool TryToInstantiatePerformanceCounter(string counterName, string instanceName, out PerformanceCounter counter)
 {
     return(TryToInstantiatePerformanceCounter(counterName, instanceName, out counter, false));
 }
예제 #38
0
        async void GetProcess()
        {
            ListItems.Clear();

            processes = Process.GetProcesses().ToList();

            var counters = new List <PerformanceCounter>();

            ObjectQuery wql = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
            ManagementObjectSearcher   searcher = new ManagementObjectSearcher(wql);
            ManagementObjectCollection results  = searcher.Get();

            long totalPhysicalMemory = 0;

            foreach (ManagementObject result in results)
            {
                totalPhysicalMemory = Int64.Parse(result["TotalVisibleMemorySize"].ToString());
            }

            foreach (var item in processes)
            {
                var counter = new PerformanceCounter("Process", "% Processor Time", item.ProcessName);
                try { counter.NextValue(); } catch { counter.NextValue(); };
                counters.Add(counter);
            }

            int i = 0;

            await Task.Delay(1000);

            foreach (var item in processes)
            {
                float counterValue = 0;
                try
                {
                    counterValue = counters[i].NextValue();
                }
                catch
                {
                }
                double CPUPercent = Math.Round(counterValue, 1);

                i++;

                var processName = ProcessExecutablePath(item);
                if (!string.IsNullOrEmpty(processName))
                {
                    Icon icon = System.Drawing.Icon.ExtractAssociatedIcon(processName);

                    ListItems.Add(new ProcessItem()
                    {
                        Id            = item.Id,
                        Name          = System.IO.Path.GetFileName(processName),
                        Icon          = ToImageSource(icon),
                        CPUPercent    = CPUPercent,
                        MemoryPercent = (item.WorkingSet64 * 100 / (totalPhysicalMemory * 1000)).ToString()
                    });;
                }
            }

            btnReload.Content = "Reload";
            canReload         = true;
        }
        static bool TryToInstantiatePerformanceCounter(string counterName, string instanceName, out PerformanceCounter counter, bool throwIfFails)
        {
            if (instanceName.Length > 128)
            {
                throw new Exception(string.Format("The endpoint name ('{0}') is too long (longer then {1}) to register as a performance counter instance name. Please reduce the endpoint name.", instanceName, (int)SByte.MaxValue));
            }

            var message = String.Format("NServiceBus performance counter for '{0}' is not set up correctly. Please run Install-NServiceBusPerformanceCounters cmdlet to rectify this problem.", counterName);

            try
            {
                counter = new PerformanceCounter("NServiceBus", counterName, instanceName, false);
            }
            catch (Exception ex)
            {
                if (throwIfFails)
                {
                    throw new InvalidOperationException(message, ex);
                }

                logger.Info(message);
                counter = null;

                return(false);
            }

            return(true);
        }
예제 #40
0
		/// <summary>
		/// Starts a stopwatch.
		/// </summary>
		/// <returns></returns>
		internal static IDisposable StartGlobalStopwatch(PerformanceCounter pc)
		{
			var pco = m_GlobalStopwatches[(int)pc];
			return (pco != null) ? pco.Start() : null;
		}
예제 #41
0
파일: Everest.cs 프로젝트: max4805/Everest
 private static float GetTotalRAMMono()
 {
     // Mono returns memory size in bytes as float.
     using (PerformanceCounter pc = new PerformanceCounter("Mono Memory", "Total Physical Memory", true))
         return(pc.NextValue() / 1024f / 1024f);
 }
예제 #42
0
        private static PerformanceCounter GetOrInstallCounter(string property, string name, string category, string instance = null)
        {
#if COREFX
            return new PerformanceCounter();
#else
            if (!Counters[Process].ContainsKey(property))
            {
                var counter = new PerformanceCounter(category, name, instance ?? Process, true);

                Counters[Process].Add(property, counter);
            }
            return Counters[Process][property];
#endif
        }
예제 #43
0
        /// <summary>
        /// Handler for project started events
        /// </summary>
        /// <param name="sender">sender (should be null)</param>
        /// <param name="e">event arguments</param>
        /// <owner>t-jeffv, sumedhk</owner>
        public override void ProjectStartedHandler(object sender, ProjectStartedEventArgs e)
        {
            if (!contextStack.IsEmpty())
            {
                this.VerifyStack(contextStack.Peek().type == FrameType.Target, "Bad stack -- Top is project {0}", contextStack.Peek().ID);
            }

            // if verbosity is normal, detailed or diagnostic
            if (IsVerbosityAtLeast(LoggerVerbosity.Normal))
            {
                ShowDeferredMessages();

                // check for stack corruption
                if (!contextStack.IsEmpty())
                {
                    this.VerifyStack(contextStack.Peek().type == FrameType.Target, "Bad stack -- Top is target {0}", contextStack.Peek().ID);
                }

                contextStack.Push(new Frame(FrameType.Project,
                                            false, // message not yet displayed
                                            this.currentIndentLevel,
                                            e.ProjectFile,
                                            e.TargetNames,
                                            null,
                                            GetCurrentlyBuildingProjectFile()));
                WriteProjectStarted();
            }
            else
            {
                contextStack.Push(new Frame(FrameType.Project,
                                            false, // message not yet displayed
                                            this.currentIndentLevel,
                                            e.ProjectFile,
                                            e.TargetNames,
                                            null,
                                            GetCurrentlyBuildingProjectFile()));
            }

            if (this.showPerfSummary)
            {
                PerformanceCounter counter = GetPerformanceCounter(e.ProjectFile, ref projectPerformanceCounters);

                // Place the counter "in scope" meaning the project is executing right now.
                counter.InScope = true;
            }

            if (Verbosity == LoggerVerbosity.Diagnostic && showItemAndPropertyList)
            {
                if (e.Properties != null)
                {
                    ArrayList propertyList = ExtractPropertyList(e.Properties);
                    WriteProperties(propertyList);
                }

                if (e.Items != null)
                {
                    SortedList itemList = ExtractItemList(e.Items);
                    WriteItems(itemList);
                }
            }
        }
예제 #44
0
    public static void mesure_init_2(List<String> names)
    {
        PlugwiseLib.BLL.BC.PlugwiseDeviceInfo calib;
        string fileName = @"C:\GreenCodeLab_Plugwyse\log.txt";
        TextWriter writer;
        writer = new StreamWriter(fileName);
        string entete = "";

        int num = 0;
        for (int i = 0; i < 9; i++)
        {
            if (Plug_act[i] == true)
            {
                calib = control.InitPlug(TimerMesure.Plug_mac[i],serialPort);
                if (calib != null)
                {
                    Plug_Ok[i] = true;
                    Plug_Calib[i] = calib;
                    if (bufferisation == false)
                    {
                        entete = entete + names[i] + ";%CPU " + (i + 1).ToString() + ";Bytes/S " + (i + 1).ToString()  + ";Disk Bytes/S " + (i + 1).ToString() + ";consommation " + (i + 1).ToString() + ";Impact consommation " + (i + 1).ToString();
                    }
                    else
                    {
                        entete = entete + names[i] + ";";
                    }
                    Array.Resize(ref Plug_num, num + 1);
                    Plug_num[num] = i;
                    num++;
                }
                else
                {
                    Plug_Ok[i] = false;
                }
            }
            else
            {
                Plug_Ok[i] = false;

            }
        }

        writer.WriteLine(entete);
        writer.Close();
        if (mesurecpu == true)
        {
            PerformanceCounterCategory networkCategory;
             string instanceName = null;

            PCounter = new PerformanceCounter();
            PCounter.MachineName = Environment.MachineName; //Attribution de la propriété MachineName permettant de "dire" au Compteur de performance de compter sur la machine local
            PCounter.CategoryName = "Processor";
            PCounter.CounterName = "% Processor Time";
            PCounter.InstanceName = "_Total";

            PCounter2 = new PerformanceCounter();
            PCounter2.MachineName = Environment.MachineName; //Attribution de la propriété MachineName permettant de "dire" au Compteur de performance de compter sur la machine local
            PCounter2.CategoryName = "Network Interface";
            PCounter2.CounterName = "Bytes Total/sec";
            networkCategory = new PerformanceCounterCategory("Network Interface");
              foreach (string instance in networkCategory.GetInstanceNames())

        {
            Console.WriteLine(instance);
            if (instance == "Realtek PCIe FE Family Controller")
            {
                instanceName = instance;
                break;
            }
        }

              PCounter2.InstanceName = instanceName;

              PCounter3 = new PerformanceCounter();
              PCounter3.MachineName = Environment.MachineName; //Attribution de la propriété MachineName permettant de "dire" au Compteur de performance de compter sur la machine local
              PCounter3.CategoryName = "PhysicalDisk";
              PCounter3.CounterName = "% Disk Time";
              PCounter3.InstanceName = "_Total";
        }
    }
예제 #45
0
파일: Program.cs 프로젝트: SpringHgui/Cpu
    // Expects 1 arg, the pid as a decimal string
    private static void Main(string[] args)
    {
        try
        {
            Console.WriteLine("请输入pid:");
            int pid = int.Parse(Console.ReadLine());

            var     sb          = new StringBuilder();
            Process process     = Process.GetProcessById(pid);
            var     counters    = new Dictionary <string, MyThreadCounterInfo>();
            var     threadInfos = new Dictionary <string, MyThreadInfo>();

            sb.AppendFormat(
                @"<html><head><title>{0}</title><style type=""text/css"">table, td{{border: 1px solid #000;border-collapse: collapse;}}</style></head><body>",
                process.ProcessName);

            Console.WriteLine("1、正在收集计数器");

            var      cate      = new PerformanceCounterCategory("Thread");
            string[] instances = cate.GetInstanceNames();
            foreach (string instance in instances)
            {
                if (instance.StartsWith(process.ProcessName, StringComparison.CurrentCultureIgnoreCase))
                {
                    var counter1 =
                        new PerformanceCounter("Thread", "ID Thread", instance, true);
                    var counter2 =
                        new PerformanceCounter("Thread", "% Processor Time", instance, true);

                    counters.Add(instance, new MyThreadCounterInfo(counter1, counter2));
                }
            }

            foreach (var pair in counters)
            {
                try
                {
                    pair.Value.IdCounter.NextValue();
                    pair.Value.ProcessorTimeCounter.NextValue();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    throw;
                }
            }

            Thread.Sleep(1000);
            foreach (var pair in counters)
            {
                try
                {
                    var info = new MyThreadInfo();
                    info.Id = pair.Value.IdCounter.NextValue().ToString();
                    info.ProcessorTimePercentage = pair.Value.ProcessorTimeCounter.NextValue().ToString("0.0");

                    threadInfos.Add(info.Id, info);
                }
                catch
                {
                }
            }

            Console.WriteLine("2、正在收集线程信息");
            ProcessThreadCollection collection = process.Threads;
            foreach (ProcessThread thread in collection)
            {
                try
                {
                    MyThreadInfo info;
                    if (threadInfos.TryGetValue(thread.Id.ToString(), out info))
                    {
                        info.UserProcessorTime = thread.UserProcessorTime.ToString();
                        info.StartTime         = thread.StartTime.ToString();
                    }
                }
                catch
                {
                }
            }

            var debugger = new MDbgEngine();

            MDbgProcess proc = null;
            try
            {
                proc = debugger.Attach(pid);
                DrainAttach(debugger, proc);

                MDbgThreadCollection tc = proc.Threads;
                Console.WriteLine("3、正在附加到进程{0}获取调用栈", pid);
                foreach (MDbgThread t in tc)
                {
                    var tempStrs = new StringBuilder();
                    foreach (MDbgFrame f in t.Frames)
                    {
                        tempStrs.AppendFormat("<br />" + f);
                    }

                    MyThreadInfo info;
                    if (threadInfos.TryGetValue(t.Id.ToString(), out info))
                    {
                        info.CallStack = tempStrs.Length == 0 ? "no managment call stack" : tempStrs.ToString();
                    }
                }
            }
            finally
            {
                if (proc != null)
                {
                    proc.Detach().WaitOne();
                }
            }

            foreach (var info in threadInfos)
            {
                sb.Append(info.Value.ToString());
                sb.Append("<hr />");
            }

            sb.Append("</body></html>");

            Console.WriteLine("4、正在生成报表");
            using (var sw = new StreamWriter(process.ProcessName + ".htm", false, Encoding.Default))
            {
                sw.Write(sb.ToString());
            }

            Process.Start(process.ProcessName + ".htm");
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }

        Console.WriteLine("运行完毕,按回车键关闭");
        Console.ReadLine();
    }
예제 #46
0
 public MySystemUptimeHeartbeatProvider()
 {
     _uptime = new PerformanceCounter("System", "System Up Time");
     _uptime.NextValue();
 }
        public static void Initialize()
        {
            try
            {
                bool recreateCounters = false;

                CounterCreationDataCollection counters = new CounterCreationDataCollection();

                if (!PerformanceCounterCategory.Exists(categoryName))
                {
                    PerformanceCounterCategory.Create(categoryName, categoryHelp, PerformanceCounterCategoryType.SingleInstance, counters);
                }

                // Create the actual counters
                if (!PerformanceCounterCategory.CounterExists(concurrentCallsName, categoryName))
                {
                    recreateCounters = true;
                }
                CounterCreationData counter = new CounterCreationData();
                counter.CounterName = concurrentCallsName;
                counter.CounterHelp = "The total number of concurrent calls.";
                counter.CounterType = PerformanceCounterType.NumberOfItems32;
                counters.Add(counter);

                if (!PerformanceCounterCategory.CounterExists(lockedLinesName, categoryName))
                {
                    recreateCounters = true;
                }
                counter             = new CounterCreationData();
                counter.CounterName = lockedLinesName;
                counter.CounterHelp = "The total number of lines that are locked and cannot be used for incoming calls.";
                counter.CounterType = PerformanceCounterType.NumberOfItems32;
                counters.Add(counter);

                if (!PerformanceCounterCategory.CounterExists(scriptsRunningName, categoryName))
                {
                    recreateCounters = true;
                }
                counter             = new CounterCreationData();
                counter.CounterName = scriptsRunningName;
                counter.CounterHelp = "The total number of scripts currently executing.";
                counter.CounterType = PerformanceCounterType.NumberOfItems32;
                counters.Add(counter);

                if (!PerformanceCounterCategory.CounterExists(totalCallsName, categoryName))
                {
                    recreateCounters = true;
                }
                counter             = new CounterCreationData();
                counter.CounterName = totalCallsName;
                counter.CounterHelp = "The total number of calls that have been answered.";
                counter.CounterType = PerformanceCounterType.NumberOfItems64;
                counters.Add(counter);

                if (!PerformanceCounterCategory.CounterExists(phonesRegisteredName, categoryName))
                {
                    recreateCounters = true;
                }
                counter             = new CounterCreationData();
                counter.CounterName = phonesRegisteredName;
                counter.CounterHelp = "The total number of IP telephones registered.";
                counter.CounterType = PerformanceCounterType.NumberOfItems32;
                counters.Add(counter);

                // Create our performance counter if it doesn't already exist
                if (recreateCounters)
                {
                    if (PerformanceCounterCategory.Exists(categoryName))
                    {
                        PerformanceCounterCategory.Delete(categoryName);
                    }

                    PerformanceCounterCategory.Create(categoryName, categoryHelp, PerformanceCounterCategoryType.SingleInstance, counters);
                }

                // Create our counter access classes
                concurrentCalls  = new PerformanceCounter(categoryName, concurrentCallsName, false);
                lockedLines      = new PerformanceCounter(categoryName, lockedLinesName, false);
                scriptsRunning   = new PerformanceCounter(categoryName, scriptsRunningName, false);
                totalCalls       = new PerformanceCounter(categoryName, totalCallsName, false);
                phonesRegistered = new PerformanceCounter(categoryName, phonesRegisteredName, false);

                ResetCounters();
            }
            catch (Exception e)
            {
                LoggingService.AddLogEntry(WOSI.CallButler.ManagementInterface.LogLevel.ErrorsOnly, "Unable to create performance monitoring WOSI.CallButler.Data." + Utils.ErrorUtils.FormatErrorString(e), true);
            }
        }
예제 #48
0
        public STPInstancePerformanceCounter(
			string instance, 
			STPPerformanceCounterType spcType)
            : this()
        {
            STPPerformanceCounters counters = STPPerformanceCounters.Instance;
            _pcs = new PerformanceCounter(
                STPPerformanceCounters._stpCategoryName,
                counters._stpPerformanceCounters[(int) spcType].Name,
                instance,
                false);
            _pcs.RawValue = _pcs.RawValue;
        }
 public SafePerformanceCounter(PerformanceCounter counter)
 {
     this.counter = counter;
 }
예제 #50
0
        private static PerformanceCounterHistoryInfo AddHistoryInfo(PerformanceCounter performanceCounter)
        {
            lock (_performanceCounterHistory)
            {
                if (_performanceCounterHistory.ContainsKey(performanceCounter.ShortName))
                {

                    _performanceCounterHistory[performanceCounter.ShortName].NumberOfInvokeTimes++;
                    _performanceCounterHistory[performanceCounter.ShortName].TotalElapsedTicks +=
                        performanceCounter.LastElapsedTicks;
                }
                else
                {
                    _performanceCounterHistory.Add(
                        performanceCounter.ShortName,
                        new PerformanceCounterHistoryInfo(
                            performanceCounter.ShortName,
                            performanceCounter.LastElapsedTicks));
                }

                return _performanceCounterHistory[performanceCounter.ShortName];
            }
        }
예제 #51
0
        private void DecodeFrame(FastJavaByteArray fastArray)
        {
            var cameraParameters = _cameraController.Camera.GetParameters();
            var width            = cameraParameters.PreviewSize.Width;
            var height           = cameraParameters.PreviewSize.Height;

            var barcodeReader = _scannerHost.ScanningOptions.BuildBarcodeReader();

            var rotate    = false;
            var newWidth  = width;
            var newHeight = height;

            // use last value for performance gain
            var cDegrees = _cameraController.LastCameraDisplayOrientationDegree;

            if (cDegrees == 90 || cDegrees == 270)
            {
                rotate    = true;
                newWidth  = height;
                newHeight = width;
            }

            ZXing.Result result = null;
            var          start  = PerformanceCounter.Start();

            /// <summary>
            ///START - Scanning Improvement, VK Apacheta Corp 11/14/2018
            ///Added a new frame to get the center part of the captured image.
            ///To create a FastJavaByteArray from the cropped captured frame and use it to decode the barcode.
            ///To decrease the processing time drastically for higher resolution cameras.
            /// </summary>
            var frame_width  = width * 3 / 5;
            var frame_height = height * 3 / 5;
            var frame_left   = width * 1 / 5;
            var frame_top    = height * 1 / 5;

            LuminanceSource fast = new FastJavaByteArrayYUVLuminanceSource(fastArray, width, height,
                                                                           //framingRectPreview?.Width() ?? width,
                                                                           // framingRectPreview?.Height() ?? height,
                                                                           frame_left,
                                                                           frame_top,
                                                                           frame_width,
                                                                           frame_height);  // _area.Left, _area.Top, _area.Width, _area.Height);

            /// <summary>
            ///END - Scanning Improvement, VK Apacheta Corp 11/14/2018
            /// </summary>
            if (rotate)
            {
                fast = fast.rotateCounterClockwise();
            }

            result = barcodeReader.Decode(fast);

            fastArray.Dispose();
            fastArray = null;

            PerformanceCounter.Stop(start,
                                    $"width: {width}, height: {height}, frame_top :{frame_top}, frame_left: {frame_left}, frame_width: {frame_width}, frame_height: {frame_height}, degrees: {cDegrees}, rotate: {rotate}; " + "Decode Time: {0} ms");

            if (result != null)
            {
                Log.Debug(MobileBarcodeScanner.TAG, "Barcode Found");

                _wasScanned = true;
                BarcodeFound?.Invoke(this, result);
                return;
            }
        }
예제 #52
0
        private EntityGame(Game game, GraphicsDeviceManager g, SpriteBatch spriteBatch, Rectangle viewport)
        {
            Game = game;
            Game.Exiting += (sender, args) => Exit();

            SpriteBatch = spriteBatch;
            Viewport = viewport;
            Assets.LoadConent(game);

            //Inject debug info into active state
            StateChanged += state => LastID = 1;
            StateChanged += state => _debugInfo = new DebugInfo(state, "DebugInfo");
            StateChanged += state => ActiveCamera = new Camera(state, "EntityEngineDefaultCamera");

            Log = new Log();
            Process p = Process.GetCurrentProcess();
            _ramCounter = new PerformanceCounter("Process", "Working Set", p.ProcessName);
            _cpuCounter = new PerformanceCounter("Process", "% Processor Time", p.ProcessName);

            MakeWindow(g, viewport);
        }
예제 #53
0
 private static void InitializeCounter()
 {
     ramCounter = new PerformanceCounter("Memory", "Available MBytes", true);
     cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total", true);
 }
예제 #54
0
    /// <summary>
    /// GetPerfStats - here's where we get the CPU usage & memory usage.  We do this in it's own
    /// function so the JITter will not JIT (and load the performance DLLs) unless the user
    /// enables it via the configuration file.
    /// </summary>
    /// <param name="memVal">the memory usage value</param>
    /// <param name="cpuVal">the cpu usage value</param>
    public void GetPerfStats(ref float memVal, ref float cpuVal, ref float pagesVal, ref float pageFaultsVal, ref float ourPageFaultsVal)
    {
        try
        {
            if (null == memCounter)
            {
                memCounter = new PerformanceCounter("Memory", "% Committed Bytes In Use");
            }
            memVal = memCounter.NextValue();
        }
        catch
        {
            memCounter = new PerformanceCounter("Memory", "% Committed Bytes In Use");
        }

        try
        {
            if (null == cpuCounter)
            {
                cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
            }
            cpuVal = cpuCounter.NextValue();
        }
        catch
        {
            cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");	// we look at the total for all CPUs
        }

        // pages / sec
        try
        {
            if (null == pagesCounter)
            {
                pagesCounter = new PerformanceCounter("Memory", "Pages/sec");
            }
            pagesVal = pagesCounter.NextValue();
        }
        catch
        {
            pagesCounter = new PerformanceCounter("Memory", "Pages/sec");
        }

        // system wide page faults / sec
        try
        {
            if (null == pageFaultsCounter)
            {
                pageFaultsCounter = new PerformanceCounter("Memory", "Page Faults/sec");
            }
            pageFaultsVal = pagesCounter.NextValue();
        }
        catch
        {
            pageFaultsCounter = new PerformanceCounter("Memory", "Page Faults/sec");
        }

        if (myProcessName == null)
        {
            myProcessName = System.Windows.Forms.Application.ExecutablePath;
            if (myProcessName.LastIndexOf(Path.PathSeparator) != -1)
            {
                myProcessName = myProcessName.Substring(myProcessName.LastIndexOf(Path.PathSeparator) + 1);
                if (myProcessName.LastIndexOf(".") != -1)
                {
                    myProcessName = myProcessName.Substring(0, myProcessName.LastIndexOf("."));
                }
            }
        }

        // our page faults / sec
        try
        {
            if (null == ourPageFaultsCounter)
            {
                ourPageFaultsCounter = new PerformanceCounter("Process", "Page Faults/sec", myProcessName);
            }
            ourPageFaultsVal = pagesCounter.NextValue();
        }
        catch
        {
            ourPageFaultsCounter = new PerformanceCounter("Process", "Page Faults/sec", myProcessName);
        }
    }
예제 #55
0
파일: Program.cs 프로젝트: SpringHgui/Cpu
 public MyThreadCounterInfo(PerformanceCounter counter1, PerformanceCounter counter2)
 {
     IdCounter            = counter1;
     ProcessorTimeCounter = counter2;
 }
예제 #56
0
        /// <summary>
        /// Returns a performance counter for a given scope (either task name or target name)
        /// from the given table.
        /// </summary>
        /// <param name="scopeName">Task name or target name.</param>
        /// <param name="table">Table that has tasks or targets.</param>
        /// <returns></returns>
        internal static PerformanceCounter GetPerformanceCounter(string scopeName, ref Hashtable table)
        {
            // Lazily construct the performance counter table.
            if (table == null)
            {
                table = new Hashtable(StringComparer.OrdinalIgnoreCase);
            }

            PerformanceCounter counter = (PerformanceCounter)table[scopeName];

            // And lazily construct the performance counter itself.
            if (counter == null)
            {
                counter = new PerformanceCounter(scopeName);
                table[scopeName] = counter;
            }

            return counter;
        }
        public IPerformanceCounter LoadCounter(string categoryName, string counterName, string instanceName, bool isReadOnly)
        {
            // See http://msdn.microsoft.com/en-us/library/356cx381.aspx for the list of exceptions
            // and when they are thrown. 
            try
            {
                var counter = new PerformanceCounter(categoryName, counterName, instanceName, isReadOnly);

                // Initialize the counter sample
                counter.NextSample();

                return new PerformanceCounterWrapper(counter);
            }
            catch (InvalidOperationException ex)
            {
                _logger.WriteError("Performance counter failed to load: " + ex.GetBaseException());
                return null;
            }
            catch (UnauthorizedAccessException ex)
            {
                _logger.WriteError("Performance counter failed to load: " + ex.GetBaseException());
                return null;
            }
            catch (Win32Exception ex)
            {
                _logger.WriteError("Performance counter failed to load: " + ex.GetBaseException());
                return null;
            }
            catch (PlatformNotSupportedException ex)
            {
                _logger.WriteError("Performance counter failed to load: " + ex.GetBaseException());
                return null;
            }
        }
예제 #58
0
 /// <summary>
 /// Removes a <see cref="PerformanceCounter"/> being monitored.
 /// </summary>
 /// <param name="counter">The <see cref="PerformanceCounter"/> object to be unmonitored.</param>
 public void RemoveCounter(PerformanceCounter counter)
 {
     lock (m_counters)
     {
         m_counters.Remove(counter);
     }
 }
예제 #59
0
 /// <summary>
 /// Adds a <see cref="PerformanceCounter"/> to be monitored.
 /// </summary>
 /// <param name="counter">The <see cref="PerformanceCounter"/> object to be monitored.</param>
 public void AddCounter(PerformanceCounter counter)
 {
     lock (m_counters)
     {
         m_counters.Add(counter);
     }
 }
예제 #60
-1
    public static void Main()
    {
        myCounter = new PerformanceCounter("Processor", @"% Processor Time", @"_Total");
        try
        {
            myCounter.NextValue().ToString();
            Thread.Sleep(100);
            Console.WriteLine("cpuPercentUsage=" + myCounter.NextValue().ToString());
        }

        catch
        {
            return;
        }
        try
        {
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(@"root\WMI", "SELECT * FROM MSAcpi_ThermalZoneTemperature");
            int i = 0;
            foreach (ManagementObject obj in searcher.Get())
            {
                Double temp = Convert.ToDouble(obj["CurrentTemperature"].ToString());
                temp = (temp - 2732) / 10.0;
                Console.WriteLine("cpuTemp" + i++ + "=" + temp);
            }
        }
        catch
        {
            return;
        }
    }