WPF 动态模拟CPU 使用率曲线图

简介:

 在工作中经常会遇到需要将一组数据绘制成曲线图的情况,最简单的方法是将数据导入Excel,然后使用绘图功能手动生成曲线图。但是如果基础数据频繁更改,则手动创建图形可能会变得枯燥乏味。本篇将利用DynamicDataDisplay  在WPF 中动态模拟CPU 使用率图表,实现动态生成曲线图。

     新建项目将DynamicDataDisplay.dll 加载到References 中,打开MainWindow.xaml 添加命名空间xmlns:d3="http://research.microsoft.com/DynamicDataDisplay/1.0"。通过<d3:ChartPlotter> 创建一个图表框架,在其中添加两条整型坐标轴,X轴:<d3:HorizontalIntegerAxis>,Y轴:<d3:VerticalIntegerAxis>。<d3:Header> 用来设置图表名称,<d3:VerticalAxisTitle> 用来设置Y轴名称。

<Window x:Class="WpfPerformance.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d3="http://research.microsoft.com/DynamicDataDisplay/1.0"
        Title="CPU Performance" Loaded="Window_Loaded" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="CPU Usage" Margin="20,10,0,0"
                       FontSize="15" FontWeight="Bold"/>
            <TextBlock x:Name="cpuUsageText" Margin="10,10,0,0"
                       FontSize="15"/>
        </StackPanel>
        <d3:ChartPlotter x:Name="plotter" Margin="10,10,20,10" Grid.Row="1">
            <d3:ChartPlotter.VerticalAxis>
                <d3:VerticalIntegerAxis />
            </d3:ChartPlotter.VerticalAxis>

            <d3:ChartPlotter.HorizontalAxis>
                <d3:HorizontalIntegerAxis />
            </d3:ChartPlotter.HorizontalAxis>

            <d3:Header Content="CPU Performance History"/>
            <d3:VerticalAxisTitle Content="Percentage"/>
        </d3:ChartPlotter>
    </Grid>
</Window>

XAML

      接下来工作需要通过C#每秒获取一次CPU使用率,并将这些数据生成坐标点(Point)绘制在图表中。 以下是MainWindow.xaml.cs 部分的代码内容。

using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Media;
using System.Windows.Threading;
using Microsoft.Research.DynamicDataDisplay;
using Microsoft.Research.DynamicDataDisplay.DataSources;

namespace WpfPerformance
{
    public partial class MainWindow : Window
    {
        private ObservableDataSource<Point> dataSource = new ObservableDataSource<Point>();
        private PerformanceCounter cpuPerformance = new PerformanceCounter();
        private DispatcherTimer timer = new DispatcherTimer();
        private int i = 0;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void AnimatedPlot(object sender, EventArgs e)
        {
            cpuPerformance.CategoryName = "Processor";
            cpuPerformance.CounterName = "% Processor Time";
            cpuPerformance.InstanceName = "_Total";

            double x = i;
            double y = cpuPerformance.NextValue();

            Point point = new Point(x, y);
            dataSource.AppendAsync(base.Dispatcher, point);

            cpuUsageText.Text = String.Format("{0:0}%", y);
            i++;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            plotter.AddLineGraph(dataSource, Colors.Green, 2, "Percentage");
            timer.Interval = TimeSpan.FromSeconds(1);
            timer.Tick += new EventHandler(AnimatedPlot);
            timer.IsEnabled = true;
            plotter.Viewport.FitToView();
        }
    }
}

     通过ObservableDataSource<Point> 动态存储图表坐标点,PerformanceCounter 获取CPU使用率数值,DispatcherTimer 计时器在规定间隔进行取数操作,整型i 作为CPU使用率坐标点的X轴数值。

private ObservableDataSource<Point> dataSource = new ObservableDataSource<Point>();
private PerformanceCounter cpuPerformance = new PerformanceCounter();
private DispatcherTimer timer = new DispatcherTimer();
private int i = 0;

     AnimatedPlot 事件用于构造坐标点,通过设置cpuPerformance 相关参数,并使用NextValue() 方法获取当前CPU使用率数据作为Y值,整型i 作为X值。将X、Y值构造为坐标点(Point),并通过异步方式存储在dataSource 中。

private void AnimatedPlot(object sender, EventArgs e)
{
    cpuPerformance.CategoryName = "Processor";
    cpuPerformance.CounterName = "% Processor Time";
    cpuPerformance.InstanceName = "_Total";

    double x = i;
    double y = cpuPerformance.NextValue();

    Point point = new Point(x, y);
    dataSource.AppendAsync(base.Dispatcher, point);

    cpuUsageText.Text = String.Format("{0:0}%", y);
    i++;
}

     最后通过Window_Loaded 将事件加载到<Window> 中,AddLineGraph 方法将dataSource 中的坐标点绘制到图表中,曲线颜色定义为绿色,粗细设置为2,曲线名称为"Percentage"。设置计时器间隔为1秒,连续执行AnimatedPlot 事件实时绘制新坐标点。

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    plotter.AddLineGraph(dataSource, Colors.Green, 2, "Percentage");
    timer.Interval = TimeSpan.FromSeconds(1);
    timer.Tick += new EventHandler(AnimatedPlot);
    timer.IsEnabled = true;
    plotter.Viewport.FitToView();
}
CPU  

鼠标右键可将图表拷贝到其他文档:

CopyPlot

动态演示

鼠标左键拖动图表浏览任意位置曲线数据,鼠标中键可以缩放显示曲线图。

Capture

源代码下载

WpfPerformance.zip






本文转自Gnie博客园博客,原文链接:http://www.cnblogs.com/gnielee/archive/2010/08/02/wpf-cpu-usage.html,如需转载请自行联系原作者

相关文章
|
16天前
|
SQL 数据管理 网络安全
数据管理DMS操作报错合集之DMS的CPU使用率达到100%,如何解决
数据管理DMS(Data Management Service)是阿里云提供的数据库管理和运维服务,它支持多种数据库类型,包括RDS、PolarDB、MongoDB等。在使用DMS进行数据库操作时,可能会遇到各种报错情况。以下是一些常见的DMS操作报错及其可能的原因与解决措施的合集。
|
2月前
|
Web App开发 Java 测试技术
ChaosBlade常见问题之演练场景页面乱码cpu使用率图片显示不出来如何解决
ChaosBlade 是一个开源的混沌工程实验工具,旨在通过模拟各种常见的硬件、软件、网络、应用等故障,帮助开发者在测试环境中验证系统的容错和自动恢复能力。以下是关于ChaosBlade的一些常见问题合集:
24 0
|
监控 算法 Linux
【C/C++ 实用工具】CPU使用率监控工具对比
【C/C++ 实用工具】CPU使用率监控工具对比
48 0
|
2月前
|
监控 Java 索引
cpu使用率过高和jvm old占用过高排查过程
cpu使用率过高和jvm old占用过高排查过程
44 2
|
6月前
|
Shell
我来教你如何将cpu使用率up起来(shell脚本[含注释])
我来教你如何将cpu使用率up起来(shell脚本[含注释])
266 0
|
6月前
|
缓存 测试技术 数据中心
【计算机架构】计算 CPU 动态功耗 | 集成电路成本 | SPEC 基准测试 | Amdahl 定律 | MIPS 性能指标
【计算机架构】计算 CPU 动态功耗 | 集成电路成本 | SPEC 基准测试 | Amdahl 定律 | MIPS 性能指标
262 0
|
7月前
|
Linux
模拟Linux服务器高cpu使用率
模拟Linux服务器高cpu使用率
|
6天前
|
缓存 监控 前端开发
如何在 Linux 命令行中检查 CPU 使用率
【5月更文挑战第8天】
16 0
|
7天前
|
监控 数据可视化 Java
Elasitcsearch CPU 使用率突然飙升,怎么办?
Elasitcsearch CPU 使用率突然飙升,怎么办?
17 1
|
1月前
|
Linux
如何在Linux系统上查看CPU使用率?
以上命令可以帮助你监视和分析Linux系统中的CPU使用率,可以根据需要选择合适的命令进行查看。 买CN2云服务器,免备案服务器,高防服务器,就选蓝易云。百度搜索:蓝易云
17 0