c# - 监控 Direct X 应用程序的 FPS

标签 c# visual-studio visual-studio-2012 directx frame-rate

我想创建一个外部应用程序来监视 DirectX 应用程序的“FPS”(例如没有录制的 FRAPS)。我读过几本 Microsoft articles on performance measuring tools - 但我希望获得社区的反馈(和经验)。

我的问题:获取 DirectX 应用程序 FPS 的最佳方法是什么?

最佳答案

Windows 有一些 Event Tracing for Windows与 DirectX 分析相关的提供商。最有趣的是 Microsoft-Windows-D3D9Microsoft-Windows-DXGI,它们允许跟踪帧显示事件。计算 FPS 的最简单方法是计算一个时间间隔内的 PresentStart 事件数,然后除以该时间间隔的长度。

要在 C# 中使用 ETW,请安装 Microsoft.Diagnostics.Tracing.TraceEvent包。

以下代码示例显示正在运行的进程的 FPS:

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Threading;
using Microsoft.Diagnostics.Tracing.Session;

namespace ConsoleApp1
{
    //helper class to store frame timestamps
    public class TimestampCollection
    {
        const int MAXNUM = 1000;

        public string Name { get; set; }

        List<long> timestamps = new List<long>(MAXNUM + 1);
        object sync = new object();

        //add value to the collection
        public void Add(long timestamp)
        {
            lock (sync)
            {
                timestamps.Add(timestamp);
                if (timestamps.Count > MAXNUM) timestamps.RemoveAt(0);
            }
        }

        //get the number of timestamps withing interval
        public int QueryCount(long from, long to)
        {
            int c = 0;

            lock (sync)
            {
                foreach (var ts in timestamps)
                {
                    if (ts >= from && ts <= to) c++;
                }
            }
            return c;
        }
    }

    class Program
    {
        //event codes (https://github.com/GameTechDev/PresentMon/blob/40ee99f437bc1061a27a2fc16a8993ee8ce4ebb5/PresentData/PresentMonTraceConsumer.cpp)
        public const int EventID_D3D9PresentStart = 1;
        public const int EventID_DxgiPresentStart = 42;

        //ETW provider codes
        public static readonly Guid DXGI_provider = Guid.Parse("{CA11C036-0102-4A2D-A6AD-F03CFED5D3C9}");
        public static readonly Guid D3D9_provider = Guid.Parse("{783ACA0A-790E-4D7F-8451-AA850511C6B9}");

        static TraceEventSession m_EtwSession;
        static Dictionary<int, TimestampCollection> frames = new Dictionary<int, TimestampCollection>();       
        static Stopwatch watch = null;
        static object sync = new object();

        static void EtwThreadProc()
        {            
            //start tracing
            m_EtwSession.Source.Process();
        }

        static void OutputThreadProc()
        {
            //console output loop
            while (true)
            {    
                long t1, t2;
                long dt = 2000;
                Console.Clear();
                Console.WriteLine(DateTime.Now.ToString() + "." + DateTime.Now.Millisecond.ToString());
                Console.WriteLine();

                lock (sync)
                {
                    t2 = watch.ElapsedMilliseconds;
                    t1 = t2 - dt;

                    foreach (var x in frames.Values)
                    {
                        Console.Write(x.Name + ": ");   

                        //get the number of frames
                        int count = x.QueryCount(t1, t2);

                        //calculate FPS
                        Console.WriteLine("{0} FPS", (double)count / dt * 1000.0);
                    }
                }

                Console.WriteLine();
                Console.WriteLine("Press any key to stop tracing...");
                Thread.Sleep(1000);
            }
        }

        public static void Main(string[] argv)
        {
            //create ETW session and register providers
            m_EtwSession = new TraceEventSession("mysess");
            m_EtwSession.StopOnDispose = true;
            m_EtwSession.EnableProvider("Microsoft-Windows-D3D9");
            m_EtwSession.EnableProvider("Microsoft-Windows-DXGI");

            //handle event
            m_EtwSession.Source.AllEvents += data =>
            {
                //filter out frame presentation events
                if (((int)data.ID == EventID_D3D9PresentStart && data.ProviderGuid == D3D9_provider) ||
                ((int)data.ID == EventID_DxgiPresentStart && data.ProviderGuid == DXGI_provider))
                {
                    int pid = data.ProcessID;
                    long t;

                    lock (sync)
                    {
                        t = watch.ElapsedMilliseconds; 

                        //if process is not yet in Dictionary, add it
                        if (!frames.ContainsKey(pid))
                        {
                            frames[pid] = new TimestampCollection();

                            string name = "";
                            var proc = Process.GetProcessById(pid);
                            if (proc != null)
                            {
                                using (proc)
                                {
                                    name = proc.ProcessName;
                                }
                            }
                            else name = pid.ToString();

                            frames[pid].Name = name;
                        }

                        //store frame timestamp in collection
                        frames[pid].Add(t);
                    }
                }
            };

            watch = new Stopwatch();
            watch.Start();            

            Thread thETW = new Thread(EtwThreadProc);
            thETW.IsBackground = true;
            thETW.Start();

            Thread thOutput = new Thread(OutputThreadProc);
            thOutput.IsBackground = true;
            thOutput.Start();

            Console.ReadKey();
            m_EtwSession.Dispose();
        }
    }
}

基于PresentMon的源代码项目。

关于c# - 监控 Direct X 应用程序的 FPS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18340347/

相关文章:

c# - 修复 C# 异步方法顺序执行

c# - 关于继承 C#

c# - 如何使用 asp.net MVC 在 GridView 中编辑数据?

visual-studio - 如何在 WSL2 和其他应用程序中打开 Visual Studio?

c++ - Opencv:二维条码(Data Matrix)检测

c++ - 将模板类型参数的映射存储到 C++ 中的 Vector : Visual Studio

c# - 检查表中是否包含列表中的值

c# - 是否可以创建一个快捷方式来将未使用的 usings 删除到一个类中?

visual-studio - 当特定版本为 False 时特定版本的程序集引用

c# - 无法加载文件或程序集 HtmlAgilityPack 版本 1.4.6.0