监测DirectX应用程序的帧率(FPS)

7

我希望创建一个外部应用程序来监控DirectX应用程序的FPS(类似于FRAPS但不包括录制)。 我已经阅读了几篇有关性能测量工具的Microsoft文章,但我正在寻求社区的反馈(和经验)。

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

3个回答

6

Windows有一些与DirectX性能分析相关的事件跟踪(Event Tracing)提供程序。最有趣的是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 项目的源代码。

2
Fraps会将一个DLL插入到每个正在运行的应用程序中,并钩取特定的DX调用以计算帧速率和捕获视频,我相信你也需要做类似的事情。经过一番探索,我找到了一个Github项目,它可以进行基本的DX hooking来进行截图和覆盖,所以这可能是一个很好的起点。虽然我个人没有使用过,所以无法完全保证其质量。

http://spazzarama.com/2011/03/14/c-screen-capture-and-overlays-for-direct3d-9-10-and-11-using-api-hooks/


0

https://dev59.com/x3XYa4cB1Zd3GeqP_uYK#54625953的基础上:

我并没有很好地使用秒表作为事件触发器,因为事件触发似乎与实际帧异步。我一次会得到20-50个帧批量,使得估计的FPS波动在实际值的50%至250%之间。

相反,我使用了TimeStampRelativeMSec。

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

        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;
        }
        frames[pid].Add((long)data.TimeStampRelativeMSec);
    }
};

从TraceEvent类中获取属性,并通过四舍五入过去任意数量条目之间的平均时间来计算FPS:

public double GetFrameTime(int count)
{
    double returnValue = 0;

    int listCount = timestamps.Count;

    if(listCount > count)
    {
        for(int i = 1; i <= count; i++)
        {
            returnValue += timestamps[listCount - i] - timestamps[listCount - (i + 1)];
        }

        returnValue /= count;
    }

    return returnValue;
}

这种方法比我试过的几款游戏内可用计数器更为精确。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接