コード例 #1
0
    void OnGUI()
    {
        if (GUILayout.Button("Take Snapshot"))
        {
            // 每次执行前先重置数据
            ResetAllData();

            // 获取快照回调
            MemorySnapshot.OnSnapshotReceived += OnSnapshotReceived;
            // 请求获取内存快照
            MemorySnapshot.RequestNewSnapshot();
        }

        if (_snapshotInfo == null)
        {
            return;
        }

        _tabIndex = GUILayout.Toolbar(_tabIndex, new[] { "NativeObjects", "ManagedType" });
        switch (_tabIndex)
        {
        case 0:
            DrawNativeUnityEngineObjectInfo();
            break;

        case 1:
            break;

        default:
            Debug.LogError("Undefine tabIndex: " + _tabIndex);
            break;
        }
    }
コード例 #2
0
    protected override void Do_GUI()
    {
        GUI.SetNextControlName("LoginIPTextField");
        var currentStr = GUILayout.TextField(_IPField, GUILayout.Width(100));

        if (!_IPField.Equals(currentStr))
        {
            _IPField = currentStr;
        }

        if (GUI.GetNameOfFocusedControl().Equals("LoginIPTextField") && _IPField.Equals(MemConst.RemoteIPDefaultText))
        {
            _IPField = "";
        }

        bool savedState = GUI.enabled;

        bool connected = /*NetManager.Instance != null && NetManager.Instance.IsConnected &&*/ MemUtil.IsProfilerConnectedRemotely;

        GUI.enabled = !connected;
        if (GUILayout.Button("Connect", GUILayout.Width(80)))
        {
            _connectPressed = true;
        }
        GUI.enabled = connected;
        if (GUILayout.Button("Take Snapshot", GUILayout.Width(100)))
        {
            MemorySnapshot.RequestNewSnapshot();
        }
        GUI.enabled = savedState;

        GUILayout.Space(DrawIndicesGrid(300, 20));
    }
コード例 #3
0
    public void WriteTypeDetails(MemorySnapshot compare)
    {
        List <KeyValuePair <string, DetailInfo> > list = null;

        if (compare != null)
        {
            list = compare.detailTypeCount.ToList();
        }
        List <KeyValuePair <string, DetailInfo> > list2 = detailTypeCount.ToList();

        list2.Sort(delegate(KeyValuePair <string, DetailInfo> x, KeyValuePair <string, DetailInfo> y)
        {
            DetailInfo value5 = y.Value;
            int count         = value5.count;
            DetailInfo value6 = x.Value;
            return(count - value6.count);
        });
        using (StreamWriter streamWriter = new StreamWriter(GarbageProfiler.GetFileName("type_details_" + detailTypeStr)))
        {
            streamWriter.WriteLine("Delta,Count,NumArrayEntries,Type");
            foreach (KeyValuePair <string, DetailInfo> item in list2)
            {
                DetailInfo value = item.Value;
                int        num   = value.count;
                if (list != null)
                {
                    foreach (KeyValuePair <string, DetailInfo> item2 in list)
                    {
                        if (item2.Key == item.Key)
                        {
                            int        num2   = num;
                            DetailInfo value2 = item2.Value;
                            num = num2 - value2.count;
                            break;
                        }
                    }
                }
                StreamWriter streamWriter2 = streamWriter;
                object[]     obj           = new object[7]
                {
                    num,
                    ",",
                    null,
                    null,
                    null,
                    null,
                    null
                };
                DetailInfo value3 = item.Value;
                obj[2] = value3.count;
                obj[3] = ",";
                DetailInfo value4 = item.Value;
                obj[4] = value4.numArrayEntries;
                obj[5] = ",";
                obj[6] = item.Key;
                streamWriter2.Write(string.Concat(obj));
            }
        }
    }
コード例 #4
0
    private static void Dump()
    {
        Debug.Log("Writing snapshot...");
        MemorySnapshot memorySnapshot = new MemorySnapshot();

        ClearFileName();
        MemorySnapshot.TypeData[] array = new MemorySnapshot.TypeData[memorySnapshot.types.Count];
        memorySnapshot.types.Values.CopyTo(array, 0);
        Array.Sort(array, 0, array.Length, new InstanceCountComparer());
        using (StreamWriter streamWriter = new StreamWriter(GetFileName("memory_instances")))
        {
            streamWriter.WriteLine("Delta,Instances,NumArrayEntries,Type Name");
            MemorySnapshot.TypeData[] array2 = array;
            foreach (MemorySnapshot.TypeData typeData in array2)
            {
                if (typeData.instanceCount != 0)
                {
                    int num = typeData.instanceCount;
                    if (previousSnapshot != null)
                    {
                        MemorySnapshot.TypeData typeData2 = MemorySnapshot.GetTypeData(typeData.type, previousSnapshot.types);
                        num = typeData.instanceCount - typeData2.instanceCount;
                    }
                    streamWriter.WriteLine(num + "," + typeData.instanceCount + "," + typeData.numArrayEntries + ",\"" + typeData.type.ToString() + "\"");
                }
            }
        }
        using (StreamWriter streamWriter2 = new StreamWriter(GetFileName("memory_hierarchies")))
        {
            streamWriter2.WriteLine("Delta,Count,Type Hierarchy");
            MemorySnapshot.TypeData[] array3 = array;
            foreach (MemorySnapshot.TypeData typeData3 in array3)
            {
                if (typeData3.instanceCount != 0)
                {
                    foreach (KeyValuePair <MemorySnapshot.HierarchyNode, int> hierarchy in typeData3.hierarchies)
                    {
                        int num2 = hierarchy.Value;
                        if (previousSnapshot != null)
                        {
                            MemorySnapshot.TypeData typeData4 = MemorySnapshot.GetTypeData(typeData3.type, previousSnapshot.types);
                            int value = 0;
                            if (typeData4.hierarchies.TryGetValue(hierarchy.Key, out value))
                            {
                                num2 = hierarchy.Value - value;
                            }
                        }
                        streamWriter2.WriteLine(num2 + "," + hierarchy.Value + ", \"" + typeData3.type.ToString() + ": " + hierarchy.Key.ToString() + "\"");
                    }
                }
            }
        }
        previousSnapshot = memorySnapshot;
        Debug.Log("Done writing snapshot!");
    }
コード例 #5
0
        public void TestFromProcess()
        {
            // Generate MemorySnapshot for Notepad.
            MemorySnapshot memorySnapshot = MemorySnapshot.FromProcess(notepad.Id);

            // Generate the oracle for comparison.
            Dictionary <string, long> oracle = GenerateOracle(notepad.Id);

            // Do a comparison of all the properties.
            VerifyProperties(memorySnapshot, oracle);
        }
コード例 #6
0
        public static void GetMemoryShapshot(MemorySnapshotCmdletBase cmdlet, int[] processIds)
        {
            if (null != processIds && 0 < processIds.Length)
            {
                foreach (int processId in processIds)
                {
                    MemorySnapshot snapshot = MemorySnapshot.FromProcess(processId);

                    cmdlet.WriteObject(cmdlet, snapshot);
                }
            }
        }
コード例 #7
0
ファイル: Program.cs プロジェクト: yeungxh/TestApi
 public static void PrintToConsole(MemorySnapshot ms)
 {
     Console.WriteLine(
         String.Format(
             format,
             ms.Timestamp.ToString() + "\t",
             ms.HandleCount + "\t", ms.GdiObjectCount + "\t", ms.UserObjectCount + "\t", ms.ThreadCount + "\t",
             ms.PageFileBytes + "\t", ms.PageFilePeakBytes + "\t", ms.PoolNonpagedBytes + "\t", ms.PoolPagedBytes + "\t",
             ms.VirtualMemoryBytes + "\t", ms.VirtualMemoryPrivateBytes + "\t",
             ms.WorkingSetBytes + "\t", ms.WorkingSetPeakBytes + "\t", ms.WorkingSetPrivateBytes + "\t"
             )
         );
 }
コード例 #8
0
    protected override void Do_GUI()
    {
        if (GUILayout.Button("Take Snapshot", EditorStyles.toolbarButton, GUILayout.Width(120), GUILayout.Height(20)))
        {
            MemorySnapshot.RequestNewSnapshot();
        }

        if (Event.current.type == EventType.Repaint)
        {
            _last = GUILayoutUtility.GetLastRect();
        }

        GUILayout.Space(DrawIndicesGrid(_last.xMax + 20, _last.y));
    }
コード例 #9
0
 private void VerifyDiff(MemorySnapshot memorySnapshot, Dictionary <string, long> oracle)
 {
     Assert.Equal(memorySnapshot.GdiObjectCount, oracle["GdiObjectCount"]);
     Assert.Equal(memorySnapshot.HandleCount, oracle["HandleCount"]);
     Assert.Equal(memorySnapshot.PageFileBytes, oracle["PageFileBytes"]);
     Assert.Equal(memorySnapshot.PageFilePeakBytes, oracle["PageFilePeakBytes"]);
     Assert.Equal(memorySnapshot.PoolNonpagedBytes, oracle["PoolNonpagedBytes"]);
     Assert.Equal(memorySnapshot.PoolPagedBytes, oracle["PoolPagedBytes"]);
     Assert.Equal(memorySnapshot.ThreadCount, oracle["ThreadCount"]);
     Assert.Equal(memorySnapshot.UserObjectCount, oracle["UserObjectCount"]);
     Assert.Equal(memorySnapshot.VirtualMemoryBytes, oracle["VirtualMemoryBytes"]);
     Assert.Equal(memorySnapshot.WorkingSetBytes, oracle["WorkingSetBytes"]);
     Assert.Equal(memorySnapshot.WorkingSetPeakBytes, oracle["WorkingSetPeakBytes"]);
     Assert.Equal(memorySnapshot.WorkingSetPrivateBytes, oracle["WorkingSetPrivateBytes"]);
 }
コード例 #10
0
        public void TestCompareTo()
        {
            // Generate a memory snapshot.
            MemorySnapshot memorySnapshot = MemorySnapshot.FromProcess(notepad.Id);

            // Generate a second MemorySnapshot and get a diff.
            MemorySnapshot latestSnap = MemorySnapshot.FromProcess(notepad.Id);
            MemorySnapshot diff       = latestSnap.CompareTo(memorySnapshot);

            // Manipulate the oracle to contain the same diff.
            Dictionary <string, long> diffOracle = GenerateDiffOracle(memorySnapshot, latestSnap);

            // Compare to verify data.
            VerifyProperties(diff, diffOracle);
        }
コード例 #11
0
        public void TestFromFile()
        {
            string filePath = @"C:\testSnap.xml";

            // Serialize MemorySnapshot to file.
            MemorySnapshot memorySnapshot = MemorySnapshot.FromProcess(notepad.Id);

            memorySnapshot.ToFile(filePath);

            // Generate the oracle for comparison.
            Dictionary <string, long> oracle = GenerateOracle(notepad.Id);

            // Call from file to load data from file.
            MemorySnapshot fileSnapshot = MemorySnapshot.FromFile(filePath);

            // Compare to data in oracle.
            VerifyProperties(fileSnapshot, oracle);
        }
コード例 #12
0
        static void Main(string[] args)
        {
            #region dependencies
            Data data = new Data(new MemorySnapShotContext());

            List <MemorySnapshot> memorySnapshots = new List <MemorySnapshot>();

            ShellCommands shellCommandsService = new ShellCommands();

            ParsingService parsingService = new ParsingService();

            long currentInterval = 0;

            int tenSeconds = (int)TimeFromMsEnums.TenSeconds;
            #endregion dependencies

            while (true)
            {
                string unparsedMemory = shellCommandsService.ExecuteLinuxCommand("free", "-m");

                MemorySnapshot ms = parsingService.ParseMemorySnapshot(unparsedMemory);

                if (ms != null)
                {
                    memorySnapshots.Add(ms);
                }
                else
                {
                    memorySnapshots.Add(new MemorySnapshot());
                }

                if (currentInterval > (int)TimeFromMsEnums.FiveMinutes)
                {
                    data.SaveMemorySnapshots(memorySnapshots);
                    memorySnapshots = new List <MemorySnapshot>();
                    currentInterval = 0;
                }

                currentInterval += tenSeconds;

                Thread.Sleep(tenSeconds);
            }
        }
コード例 #13
0
        public void TestToFile()
        {
            string filePath = @"C:\testSnap.xml";

            // Store call ToFile to log memorySnapshot to file.
            MemorySnapshot memorySnapshot = MemorySnapshot.FromProcess(notepad.Id);

            memorySnapshot.ToFile(filePath);

            // Generate the oracle for comparison.
            Dictionary <string, long> oracle = GenerateOracle(notepad.Id);

            // Go through xml nodes and compare to data in oracle.
            XmlDocument xmlDoc = new XmlDocument();

            using (Stream s = new FileInfo(filePath).OpenRead())
            {
                try
                {
                    xmlDoc.Load(s);
                }
                catch (XmlException)
                {
                    throw new XmlException("MemorySnapshot file \"" + filePath + "\" could not be loaded.");
                }
            }

            // Grab memory stats.
            Assert.Equal(oracle["GdiObjectCount"], DeserializeNode(xmlDoc, "GdiObjectCount"));
            Assert.Equal(oracle["HandleCount"], DeserializeNode(xmlDoc, "HandleCount"));
            Assert.Equal(oracle["PageFileBytes"], DeserializeNode(xmlDoc, "PageFileBytes"));
            Assert.Equal(oracle["PageFilePeakBytes"], DeserializeNode(xmlDoc, "PageFilePeakBytes"));
            Assert.Equal(oracle["PoolNonpagedBytes"], DeserializeNode(xmlDoc, "PoolNonpagedBytes"));
            Assert.Equal(oracle["PoolPagedBytes"], DeserializeNode(xmlDoc, "PoolPagedBytes"));
            Assert.Equal(oracle["ThreadCount"], DeserializeNode(xmlDoc, "ThreadCount"));
            Assert.Equal(oracle["UserObjectCount"], DeserializeNode(xmlDoc, "UserObjectCount"));
            Assert.Equal(oracle["VirtualMemoryBytes"], DeserializeNode(xmlDoc, "VirtualMemoryBytes"));
            Assert.Equal(oracle["VirtualMemoryPrivateBytes"], DeserializeNode(xmlDoc, "VirtualMemoryPrivateBytes"));
            Assert.Equal(oracle["WorkingSetBytes"], DeserializeNode(xmlDoc, "WorkingSetBytes"));
            Assert.Equal(oracle["WorkingSetPeakBytes"], DeserializeNode(xmlDoc, "WorkingSetPeakBytes"));
            Assert.Equal(oracle["WorkingSetPrivateBytes"], DeserializeNode(xmlDoc, "WorkingSetPrivateBytes"));
        }
コード例 #14
0
        private Dictionary <string, long> GenerateDiffOracle(MemorySnapshot originalSnapshot, MemorySnapshot latestSnapshot)
        {
            Dictionary <string, long> diffOracle = new Dictionary <string, long>();

            // Create oracle with correct data to verify against.
            diffOracle.Add("GdiObjectCount", latestSnapshot.GdiObjectCount - originalSnapshot.GdiObjectCount);
            diffOracle.Add("HandleCount", latestSnapshot.HandleCount - originalSnapshot.HandleCount);
            diffOracle.Add("PageFileBytes", latestSnapshot.PageFileBytes - originalSnapshot.PageFileBytes);
            diffOracle.Add("PageFilePeakBytes", latestSnapshot.PageFilePeakBytes - originalSnapshot.PageFilePeakBytes);
            diffOracle.Add("PoolNonpagedBytes", latestSnapshot.PoolNonpagedBytes - originalSnapshot.PoolNonpagedBytes);
            diffOracle.Add("PoolPagedBytes", latestSnapshot.PoolPagedBytes - originalSnapshot.PoolPagedBytes);
            diffOracle.Add("ThreadCount", latestSnapshot.ThreadCount - originalSnapshot.ThreadCount);
            diffOracle.Add("UserObjectCount", latestSnapshot.UserObjectCount - originalSnapshot.UserObjectCount);
            diffOracle.Add("VirtualMemoryBytes", latestSnapshot.VirtualMemoryBytes - originalSnapshot.VirtualMemoryBytes);
            diffOracle.Add("VirtualMemoryPrivateBytes", latestSnapshot.VirtualMemoryPrivateBytes - originalSnapshot.VirtualMemoryPrivateBytes);
            diffOracle.Add("WorkingSetBytes", latestSnapshot.WorkingSetBytes - originalSnapshot.WorkingSetBytes);
            diffOracle.Add("WorkingSetPeakBytes", latestSnapshot.WorkingSetPeakBytes - originalSnapshot.WorkingSetPeakBytes);
            diffOracle.Add("WorkingSetPrivateBytes", latestSnapshot.WorkingSetPrivateBytes - originalSnapshot.WorkingSetPrivateBytes);

            return(diffOracle);
        }
コード例 #15
0
ファイル: ProcMgr.cs プロジェクト: rouchen/UnityDemo
    /// <summary>
    ///
    /// </summary>
    public void Update()
    {
#if (!RELEASE)
        //! 流程暫停功能.
        if (Input.GetKeyDown(KeyCode.Space))
        {
            isPauseProc = !isPauseProc;
        }

        if (isPauseProc)
        {
            return;
        }
#endif // (!RELEASE).

        if (currProc == null)
        {
            return;
        }

        if (isEnterProc)
        {
            currProc.ProcStart();
            isEnterProc = false;
            //! 記憶體快照.
            MemorySnapshot.WriteMemoryProfile(FileDirectory.GetReWritePath(), currProcName);
        }

        currProc.ProcInput();
        currProc.ProcUpdate();

        //換 Proc.
        if (isChangeProc)
        {
            currProc.ProcEnd();
            SetCurrProc(nextProcName);
            isEnterProc  = true;
            isChangeProc = false;
        }
    }
コード例 #16
0
ファイル: MemoryAlarmProbe.cs プロジェクト: ahives/HareDu1
        public ProbeResult Execute <T>(T snapshot)
        {
            MemorySnapshot data = snapshot as MemorySnapshot;
            ProbeResult    result;

            var probeData = new List <ProbeData>
            {
                new ProbeDataImpl("Memory.FreeAlarm", data.AlarmInEffect.ToString()),
                new ProbeDataImpl("Memory.Limit", data.Limit.ToString()),
                new ProbeDataImpl("Memory.Used", data.Used.ToString())
            };

            if (data.AlarmInEffect)
            {
                _kb.TryGet(Metadata.Id, ProbeResultStatus.Unhealthy, out var article);
                result = new UnhealthyProbeResult(data.NodeIdentifier,
                                                  null,
                                                  Metadata.Id,
                                                  Metadata.Name,
                                                  ComponentType,
                                                  probeData,
                                                  article);
            }
            else
            {
                _kb.TryGet(Metadata.Id, ProbeResultStatus.Healthy, out var article);
                result = new HealthyProbeResult(data.NodeIdentifier,
                                                null,
                                                Metadata.Id,
                                                Metadata.Name,
                                                ComponentType,
                                                probeData,
                                                article);
            }

            NotifyObservers(result);

            return(result);
        }
コード例 #17
0
        public void TestToFromFile()
        {
            string filePath = @"C:\testSnapCollection.xml";

            MemorySnapshotCollection collection = new MemorySnapshotCollection();

            // The following is for testing purposes and not representative use of the MemorySnapshotCollection class.
            MemorySnapshot ms1 = MemorySnapshot.FromProcess(notepad.Id);

            collection.Add(ms1);
            MemorySnapshot ms2 = MemorySnapshot.FromProcess(notepad.Id);

            collection.Add(ms2);
            MemorySnapshot ms3 = MemorySnapshot.FromProcess(notepad.Id);

            collection.Add(ms3);

            // Serialize MemorySnapshot to file.
            collection.ToFile(filePath);

            // Call from file to load data from file.
            MemorySnapshotCollection fileCollection = MemorySnapshotCollection.FromFile(filePath);

            // Verify Count.
            Assert.Equal(fileCollection.Count, collection.Count);

            // Generate Diffs for comparison.
            MemorySnapshot diff1 = ms1.CompareTo(fileCollection[0]);
            MemorySnapshot diff2 = ms2.CompareTo(fileCollection[1]);
            MemorySnapshot diff3 = ms3.CompareTo(fileCollection[2]);

            // Generate expected Diff results.
            Dictionary <string, long> diffOracle = GenerateDiffOracle();

            // Verify Diffs are as expected.
            VerifyDiff(diff1, diffOracle);
            VerifyDiff(diff2, diffOracle);
            VerifyDiff(diff3, diffOracle);
        }
コード例 #18
0
        public void Run(int detectionCycles, int actionsPerCycle)
        {
            //TODO1: Launch memorysnapshot monitor as a seperate process so as not to incur extra load.

            Type     type     = this.GetType();
            LeakTest leakTest = (LeakTest)Activator.CreateInstance(type);

            // Create new memory snapshot collection and get a handle to the process.
            MemorySnapshotCollection collection = new MemorySnapshotCollection();
            Process process = Process.GetCurrentProcess();

            //TODO2: Add GC cleanup / get ready logic.

            leakTest.Initialize();
            collection.Add(MemorySnapshot.FromProcess(process.Id));

            // Rinse and repeat the following as requested by the user.
            for (int i = 0; i < detectionCycles; i++)
            {
                for (int j = 0; j < actionsPerCycle; j++)
                {
                    // Perform and undo action followed by a snapshot.
                    leakTest.PerformAction();
                    leakTest.UndoAction();
                }
                collection.Add(MemorySnapshot.FromProcess(process.Id));
            }

            // Log collection to file.
            string filePath = Path.Combine(Environment.CurrentDirectory, @"snapshots.xml");

            collection.ToFile(filePath);
            TestLog log = new TestLog("LeakLog");

            log.LogFile(filePath);
            log.Close();
        }
コード例 #19
0
ファイル: Program.cs プロジェクト: yeungxh/TestApi
        public static void Main(string[] args)
        {
            CommandLineArguments a = Init(args);

            if (a == null)
            {
                PrintUsage();
                return;
            }

            if (a.ProcessName != null)
            {
                Process[] processlist  = Process.GetProcesses();
                int       processFound = 0;

                foreach (Process p in processlist)
                {
                    if (string.Equals(a.ProcessName, p.ProcessName, StringComparison.OrdinalIgnoreCase))
                    {
                        processFound++;
                        a.Pid = p.Id;
                    }
                }

                if (processFound == 0)
                {
                    Console.WriteLine("ProcessName not found. Starting new instance...");
                    Process p = new Process();
                    p.StartInfo.FileName = a.ProcessName;
                    p.Start();
                    a.Pid = p.Id;
                    p.WaitForInputIdle();
                }

                if (processFound > 1)
                {
                    Console.WriteLine("Found multiple processes with the same name. Please specify a /pid.");
                    return;
                }
            }

            Console.WriteLine("Hit \"Ctrl^C\" to exit.");
            Console.WriteLine("Attaching to Process ID: " + a.Pid);
            Console.WriteLine("Generating memory snapshots...");

            Console.CancelKeyPress += new ConsoleCancelEventHandler(ConsoleOnCancelKeyPress);
            MemorySnapshotCollection msc = new MemorySnapshotCollection();

            if (a.InitialDelay != null)
            {
                Thread.Sleep(a.InitialDelay.Value);
            }

            PrintHeader();
            MemorySnapshot ms;

            while (true)
            {
                if (exitLoop == true)
                {
                    break;
                }

                try
                {
                    ms = MemorySnapshot.FromProcess(a.Pid.Value);
                }
                catch (ArgumentException e)
                {
                    Console.WriteLine("Process no longer avilable. Terminating MemoryTracer...");
                    return;
                }


                PrintToConsole(ms);
                if (a.SaveTo != null)
                {
                    msc.Add(ms);
                }

                Thread.Sleep(a.Interval.Value);
            }

            if (a.SaveTo != null)
            {
                msc.ToFile(a.SaveTo);
                Console.WriteLine("MemorySnapshots saved to: " + a.SaveTo);
            }
        }
コード例 #20
0
    public static void DebugDumpGarbageStats()
    {
        Debug.Log("Writing reference stats...");
        MemorySnapshot memorySnapshot = new MemorySnapshot();

        ClearFileName();
        MemorySnapshot.TypeData[] array = new MemorySnapshot.TypeData[memorySnapshot.types.Count];
        memorySnapshot.types.Values.CopyTo(array, 0);
        Array.Sort(array, 0, array.Length, new InstanceCountComparer());
        using (StreamWriter streamWriter = new StreamWriter(GetFileName("garbage_instances")))
        {
            MemorySnapshot.TypeData[] array2 = array;
            foreach (MemorySnapshot.TypeData typeData in array2)
            {
                if (typeData.instanceCount != 0)
                {
                    int num = typeData.instanceCount;
                    if (previousSnapshot != null)
                    {
                        MemorySnapshot.TypeData typeData2 = MemorySnapshot.GetTypeData(typeData.type, previousSnapshot.types);
                        num = typeData.instanceCount - typeData2.instanceCount;
                    }
                    streamWriter.WriteLine(num + ", " + typeData.instanceCount + ", \"" + typeData.type.ToString() + "\"");
                }
            }
        }
        Array.Sort(array, 0, array.Length, new RefCountComparer());
        using (StreamWriter streamWriter2 = new StreamWriter(GetFileName("garbage_refs")))
        {
            MemorySnapshot.TypeData[] array3 = array;
            foreach (MemorySnapshot.TypeData typeData3 in array3)
            {
                if (typeData3.refCount != 0)
                {
                    int num2 = typeData3.refCount;
                    if (previousSnapshot != null)
                    {
                        MemorySnapshot.TypeData typeData4 = MemorySnapshot.GetTypeData(typeData3.type, previousSnapshot.types);
                        num2 = typeData3.refCount - typeData4.refCount;
                    }
                    streamWriter2.WriteLine(num2 + ", " + typeData3.refCount + ", \"" + typeData3.type.ToString() + "\"");
                }
            }
        }
        MemorySnapshot.FieldCount[] array4 = new MemorySnapshot.FieldCount[memorySnapshot.fieldCounts.Count];
        memorySnapshot.fieldCounts.Values.CopyTo(array4, 0);
        Array.Sort(array4, 0, array4.Length, new FieldCountComparer());
        using (StreamWriter streamWriter3 = new StreamWriter(GetFileName("garbage_fields")))
        {
            MemorySnapshot.FieldCount[] array5 = array4;
            foreach (MemorySnapshot.FieldCount fieldCount in array5)
            {
                int num3 = fieldCount.count;
                if (previousSnapshot != null)
                {
                    foreach (KeyValuePair <int, MemorySnapshot.FieldCount> fieldCount2 in previousSnapshot.fieldCounts)
                    {
                        if (fieldCount2.Value.name == fieldCount.name)
                        {
                            num3 = fieldCount.count - fieldCount2.Value.count;
                            break;
                        }
                    }
                }
                streamWriter3.WriteLine(num3 + ", " + fieldCount.count + ", \"" + fieldCount.name + "\"");
            }
        }
        memorySnapshot.WriteTypeDetails(previousSnapshot);
        previousSnapshot = memorySnapshot;
        Debug.Log("Done writing reference stats!");
    }
コード例 #21
0
        void OnGUI()
        {
            Init();
            EditorGUILayout.BeginHorizontal(EditorStyles.toolbar);
            //string[] array3 = new string[] { "Editor", "F****r", "Sucker" };

            if (GUILayout.Button(new GUIContent("Active Profler"), EditorStyles.toolbarDropDown))
            {
                Rect titleRect2 = EditorGUILayout.GetControlRect();
                titleRect2.y   += EditorStyles.toolbarDropDown.fixedHeight;
                connectionGuids = ProfilerDriver.GetAvailableProfilers();
                GUIContent[] guiContents = new GUIContent[connectionGuids.Length];
                for (int i = 0; i < connectionGuids.Length; i++)
                {
                    if (connectionGuids[i] == ProfilerDriver.connectedProfiler)
                    {
                        selectedIndex = i;
                    }
                    bool   flag = ProfilerDriver.IsIdentifierConnectable(connectionGuids[i]);
                    string text = ProfilerDriver.GetConnectionIdentifier(connectionGuids[i]);
                    if (!flag)
                    {
                        text += " (Version mismatch)";//I don't know what this means...
                    }
                    guiContents[i] = new GUIContent(text);
                }
                EditorUtility.DisplayCustomMenu(titleRect2, guiContents, selectedIndex, OnSelectProfilerClick, null);
            }
            //EditorGUILayout.Popup(selectedIndex, array3, EditorStyles.toolbarPopup);

            if (GUILayout.Button("Take Sample: " + ProfilerDriver.GetConnectionIdentifier(ProfilerDriver.connectedProfiler), EditorStyles.toolbarButton))
            {
                //ProfilerDriver.ClearAllFrames();
                //ProfilerDriver.deepProfiling = true;
                ShowNotification(new GUIContent("Waiting for device..."));
                MemorySnapshot.RequestNewSnapshot();
            }
            if (GUILayout.Button(new GUIContent("Clear Editor References", "Design for profile in editor.\nEditorUtility.UnloadUnusedAssetsImmediate() can be called."), EditorStyles.toolbarButton))
            {
                ClearEditorReferences();
            }
            GUILayout.FlexibleSpace();
            //GUILayout.Space(5);
            EditorGUILayout.EndHorizontal();



            EditorGUILayout.BeginHorizontal();
            if (GUILayout.Button("Save Snapshot", EditorStyles.toolbarButton))
            {
                if (data.mSnapshot != null)
                {
                    string filePath = EditorUtility.SaveFilePanel("Save Snapshot", null, "MemorySnapshot" + System.DateTime.Now.ToString("_MMdd_HHmm"), "memsnap");
                    if (!string.IsNullOrEmpty(filePath))
                    {
                        System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                        using (Stream stream = File.Open(filePath, FileMode.Create))
                        {
                            bf.Serialize(stream, data.mSnapshot);
                        }
                    }
                }
                else
                {
                    Debug.LogWarning("No snapshot to save.  Try taking a snapshot first.");
                }
            }
            if (GUILayout.Button("Load Snapshot", EditorStyles.toolbarButton))
            {
                string filePath = EditorUtility.OpenFilePanel("Load Snapshot", null, "memsnap");
                if (!string.IsNullOrEmpty(filePath))
                {
                    System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    using (Stream stream = File.Open(filePath, FileMode.Open))
                    {
                        IncomingSnapshot(bf.Deserialize(stream) as PackedMemorySnapshot);
                    }
                }
            }
            GUILayout.FlexibleSpace();
            if (GUILayout.Button("Save Snapshot as .txt", EditorStyles.toolbarButton))
            {
                if (memoryRootNode != null)
                {
                    string filePath = EditorUtility.SaveFilePanel("Save Snapshot as .txt", null, "Mindmap" + System.DateTime.Now.ToString("_MMdd_HHmm"), "txt");
                    if (!string.IsNullOrEmpty(filePath))
                    {
                        SaveToMindMap(filePath);
                    }
                }
                else
                {
                    Debug.LogWarning("No snapshot to save.  Try taking a snapshot first.");
                }
            }
            if (GUILayout.Button("Load Snapshot from .txt", EditorStyles.toolbarButton))
            {
                string filePath = EditorUtility.OpenFilePanel("Load Snapshot from .txt", null, "txt");
                if (!string.IsNullOrEmpty(filePath))
                {
                    LoadFromMindMap(filePath);
                }
            }
            canSaveDetails = GUILayout.Toggle(canSaveDetails, "saveDetails");
            savedMinSize   = EditorGUILayout.IntField("minSize", savedMinSize, EditorStyles.toolbarTextField);
            if (savedMinSize < 0)
            {
                savedMinSize = 0;
            }
            EditorGUILayout.EndHorizontal();
            //Top tool bar end...


            EditorGUILayout.BeginHorizontal(EditorStyles.toolbar);
            memoryFilters = EditorGUILayout.ObjectField(memoryFilters, typeof(MemoryFilterSettings), false) as MemoryFilterSettings;
            //if (GUILayout.Button(new GUIContent("Save as plist/xml", "TODO in the future..."), EditorStyles.toolbarButton))
            //{
            //}
            //if (GUILayout.Button(new GUIContent("Load plist/xml", "TODO in the future..."), EditorStyles.toolbarButton))
            //{
            //}
            GUILayout.FlexibleSpace();
            GUILayout.Label(new GUIContent("[LastRefreshTime]" + lastRefreshTime.ToShortTimeString(),
                                           " enter / exit play mode or change a script,Unity has to reload the mono assemblies , and the GoProfilerWindow has to Refresh immediately"));
            if (GUILayout.Button(EditorGUIUtility.IconContent("TreeEditor.Refresh"), EditorStyles.toolbarButton, GUILayout.Width(30)))
            {
                IncomingSnapshot(data.mSnapshot);
                Repaint();
            }
            EditorGUILayout.EndHorizontal();
            if (!memoryFilters)
            {
                EditorGUILayout.HelpBox("Please Select a MemoryFilters object or load it from the .plist/.xml file", MessageType.Warning);
            }

            //TODO: handle the selected object.
            //EditorGUILayout.HelpBox("Watching Texture Detail Data is only for Editor.", MessageType.Warning, true);
            if (selectedObject != null && selectedObject.childList.Count == 0)
            {
                if (selectedObject != null && _prevInstance != selectedObject.instanceID)
                {
                    objectField   = EditorUtility.InstanceIDToObject(selectedObject.instanceID);
                    _prevInstance = selectedObject.instanceID;
                    //Selection.instanceIDs = new int[] { selectedObject.instanceID }; //Hide in inspector.
                }
            }
            if (objectField != null)
            {
                EditorGUILayout.BeginHorizontal();
                EditorGUILayout.LabelField("Selected Object Info:");
                EditorGUILayout.ObjectField(objectField, objectField.GetType(), true);
                GUILayout.FlexibleSpace();
                EditorGUILayout.EndHorizontal();
            }
            else
            {
                EditorGUILayout.LabelField("Can't instance object,maybe it was already released.");
            }
            //MemoryFilters end...

            Rect titleRect = EditorGUILayout.GetControlRect();

            EditorGUI.DrawRect(titleRect, new Color(0.15f, 0.15f, 0.15f, 1));
            EditorGUI.DrawRect(new Rect(titleRect.x + titleRect.width - 200, titleRect.y, 1, Screen.height), new Color(0.15f, 0.15f, 0.15f, 1));
            EditorGUI.DrawRect(new Rect(titleRect.x + titleRect.width - 100, titleRect.y, 1, Screen.height), new Color(0.15f, 0.15f, 0.15f, 1));
            GUI.Label(new Rect(titleRect.x, titleRect.y, titleRect.width - 200, titleRect.height), "Name", toolBarStyle);
            GUI.Label(new Rect(titleRect.x + titleRect.width - 175, titleRect.y, 50, titleRect.height), "Size", toolBarStyle);
            GUI.Label(new Rect(titleRect.x + titleRect.width - 75, titleRect.y, 50, titleRect.height), "RefCount", toolBarStyle);
            //Title bar end...

            scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition);
            if (memoryRootNode != null && memoryRootNode.childList != null)
            {
                memoryRootNode.DrawGUI(0);
            }
            else
            {
                Init();
            }
            GUILayout.EndScrollView();
            //Contents end...
            //handle the select event to Repaint
            if (Event.current.type == EventType.mouseDown)
            {
                Repaint();
            }
        }
コード例 #22
0
//		[MenuItem("性能分析/捕获快照和原生内存")]
        public static void CaptureWithNativeMemeory()
        {
            MemorySnapshot.OnSnapshotReceived += OnSnapshotCompleteForCrawling;
            MemorySnapshot.RequestNewSnapshot();
        }
コード例 #23
0
 public static void Capture()
 {
     MemorySnapshot.OnSnapshotReceived += OnSnapshotComplete;
     MemorySnapshot.RequestNewSnapshot();
 }
コード例 #24
0
        public void PrintMemorySnapshot()
        {
            MemorySnapshot m = SystemHelper.GetMemorySnapshot();

            Console.WriteLine(m);
        }
コード例 #25
0
        void OnGUI()
        {
            //if put these code to OnEnable function,the EditorStyles.boldLabel is null , and everything is wrong.
            //Debug.Log("ONGUI");
            EditorGUILayout.BeginHorizontal(EditorStyles.toolbar);
            if (GUILayout.Button("Take Sample: " + ProfilerDriver.GetConnectionIdentifier(ProfilerDriver.connectedProfiler), EditorStyles.toolbarButton))
            {
                ProfilerDriver.ClearAllFrames();
                ProfilerDriver.deepProfiling = true;
                MemorySnapshot.RequestNewSnapshot();
            }
            if (GUILayout.Button(new GUIContent("Clear Editor References", "Design for profile in editor.\nEditorUtility.UnloadUnusedAssetsImmediate() can be called."), EditorStyles.toolbarButton))
            {
                ClearEditorReferences();
            }
            if (GUILayout.Button("Save Snapshot", EditorStyles.toolbarButton))
            {
                if (data.mSnapshot != null)
                {
                    string fileName = EditorUtility.SaveFilePanel("Save Snapshot", null, "MemorySnapshot", "memsnap");
                    if (!string.IsNullOrEmpty(fileName))
                    {
                        System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                        using (Stream stream = File.Open(fileName, FileMode.Create))
                        {
                            bf.Serialize(stream, data.mSnapshot);
                        }
                    }
                }
                else
                {
                    UnityEngine.Debug.LogWarning("No snapshot to save.  Try taking a snapshot first.");
                }
            }
            if (GUILayout.Button("Load Snapshot", EditorStyles.toolbarButton))
            {
                string fileName = EditorUtility.OpenFilePanel("Load Snapshot", null, "memsnap");
                if (!string.IsNullOrEmpty(fileName))
                {
                    System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    using (Stream stream = File.Open(fileName, FileMode.Open))
                    {
                        IncomingSnapshot(bf.Deserialize(stream) as PackedMemorySnapshot);
                    }
                }
            }
            GUILayout.FlexibleSpace();
            //showObjectInspector = EditorGUILayout.Toggle("Show In Inspector", showObjectInspector); //TODO
            EditorGUILayout.EndHorizontal();
            //Top tool bar end...


            EditorGUILayout.BeginHorizontal(EditorStyles.toolbar);
            memoryFilters = EditorGUILayout.ObjectField(memoryFilters, typeof(MemoryFilterSettings), false) as MemoryFilterSettings;
            if (GUILayout.Button(new GUIContent("Save as plist/xml", "TODO in the future..."), EditorStyles.toolbarButton))
            {
            }
            if (GUILayout.Button(new GUIContent("Load plist/xml", "TODO in the future..."), EditorStyles.toolbarButton))
            {
            }
            GUILayout.FlexibleSpace();
            if (GUILayout.Button(EditorGUIUtility.IconContent("TreeEditor.Refresh"), EditorStyles.toolbarButton, GUILayout.Width(30)))
            {
                IncomingSnapshot(data.mSnapshot);
                Repaint();
            }
            EditorGUILayout.EndHorizontal();
            if (!memoryFilters)
            {
                EditorGUILayout.HelpBox("Please Select a MemoryFilters object or load it from the .plist/.xml file", MessageType.Warning);
            }

            //TODO: handle the selected object.
            //EditorGUILayout.HelpBox("Watching Texture Detail Data is only for Editor.", MessageType.Warning, true);
            if (selectedObject != null && selectedObject.childList.Count == 0)
            {
                if (selectedObject != null && _prevInstance != selectedObject.instanceID)
                {
                    objectField           = EditorUtility.InstanceIDToObject(selectedObject.instanceID);
                    _prevInstance         = selectedObject.instanceID;
                    Selection.instanceIDs = new int[] { selectedObject.instanceID };
                }
            }
            if (objectField != null)
            {
                EditorGUILayout.BeginHorizontal();
                EditorGUILayout.LabelField("Selected Object Info:");
                EditorGUILayout.ObjectField(objectField, objectField.GetType(), true);
                GUILayout.FlexibleSpace();
                EditorGUILayout.EndHorizontal();
            }
            else
            {
                EditorGUILayout.LabelField("Can't instance object,maybe it was already released.");
            }
            //MemoryFilters end...

            Rect titleRect = EditorGUILayout.GetControlRect();

            EditorGUI.DrawRect(titleRect, new Color(0.15f, 0.15f, 0.15f, 1));
            EditorGUI.DrawRect(new Rect(titleRect.x + titleRect.width - 200, titleRect.y, 1, Screen.height), new Color(0.15f, 0.15f, 0.15f, 1));
            EditorGUI.DrawRect(new Rect(titleRect.x + titleRect.width - 100, titleRect.y, 1, Screen.height), new Color(0.15f, 0.15f, 0.15f, 1));
            GUI.Label(new Rect(titleRect.x, titleRect.y, titleRect.width - 200, titleRect.height), "Name", toolBarStyle);
            GUI.Label(new Rect(titleRect.x + titleRect.width - 175, titleRect.y, 50, titleRect.height), "Size", toolBarStyle);
            GUI.Label(new Rect(titleRect.x + titleRect.width - 75, titleRect.y, 50, titleRect.height), "RefCount", toolBarStyle);
            //Title bar end...

            scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition);
            if (memoryRootNode != null && memoryRootNode.childList != null)
            {
                memoryRootNode.DrawGUI(0);
            }
            else
            {
                Init();
            }
            GUILayout.EndScrollView();
            //Contents end...
            //handle the select event to Repaint
            if (Event.current.type == EventType.mouseDown)
            {
                Repaint();
            }
        }
コード例 #26
0
ファイル: SwarmConnect.cs プロジェクト: sora-jp/leak
 private void OnMemorySnapshot(MemorySnapshot data)
 {
     Notifications.Enqueue(new MemorySnapshotNotification(data.Allocation));
 }