Compare commits
3 Commits
43de86ee31
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 4ad23a3800 | |||
| 6818de280b | |||
| 7ee76113c9 |
2
.gitignore
vendored
2
.gitignore
vendored
@@ -11,3 +11,5 @@ CTestTestfile.cmake
|
||||
_deps
|
||||
/.vs
|
||||
/out
|
||||
bin/
|
||||
out/
|
||||
@@ -3,9 +3,11 @@ project(TestTracy)
|
||||
|
||||
# 可用的选项:TRACY_ENABLE,TRACY_ON_DEMAND,TRACY_NO_BROADCAST,TRACY_NO_CODE_TRANSFER , ...
|
||||
# 在add_subdirectory之前设置选项
|
||||
option (TRACY_ENABLE "" ON)
|
||||
option (TRACY_ON_DEMAND "" ON)
|
||||
option (IS_TRACY_ENABLE "" ON)
|
||||
option (IS_TRACY_ON_DEMAND "" ON)
|
||||
add_subdirectory ("thirdparty/tracy")
|
||||
#链接 `Tracy::TracyClient` 到你想要用Tracy进行性能分析的目标。
|
||||
add_executable(MyProject main.cpp)
|
||||
target_link_libraries (MyProject PUBLIC Tracy::TracyClient)
|
||||
add_executable(TracyProject test.cpp)
|
||||
target_link_libraries (TracyProject PUBLIC Tracy::TracyClient)
|
||||
|
||||
add_subdirectory("unity_examples")
|
||||
@@ -10,18 +10,6 @@
|
||||
"cmakeCommandArgs": "",
|
||||
"buildCommandArgs": "",
|
||||
"ctestCommandArgs": ""
|
||||
},
|
||||
{
|
||||
"name": "x64-Release",
|
||||
"generator": "Ninja",
|
||||
"configurationType": "RelWithDebInfo",
|
||||
"buildRoot": "${projectDir}\\out\\build\\${name}",
|
||||
"installRoot": "${projectDir}\\out\\install\\${name}",
|
||||
"cmakeCommandArgs": "",
|
||||
"buildCommandArgs": "",
|
||||
"ctestCommandArgs": "",
|
||||
"inheritEnvironments": [ "msvc_x64_x64" ],
|
||||
"variables": []
|
||||
}
|
||||
]
|
||||
}
|
||||
112
README_TEST.md
112
README_TEST.md
@@ -1,112 +0,0 @@
|
||||
# Tracy 性能测试代码说明
|
||||
|
||||
这个项目包含多个高性能计算测试用例,用于展示 Tracy 性能分析器的功能。
|
||||
|
||||
## 测试内容
|
||||
|
||||
### 1. 矩阵乘法 (Matrix Multiplication)
|
||||
- 200x200 矩阵相乘
|
||||
- 展示计算密集型操作的性能
|
||||
- 三重循环,复杂度 O(n³)
|
||||
|
||||
### 2. 快速排序 (Quick Sort)
|
||||
- 对 100,000 个随机整数进行排序
|
||||
- 展示递归算法的性能特征
|
||||
- 平均复杂度 O(n log n)
|
||||
|
||||
### 3. 质数计算 (Prime Numbers)
|
||||
- 使用埃拉托斯特尼筛法
|
||||
- 计算 0-1,000,000 范围内的所有质数
|
||||
- 展示循环嵌套和内存访问模式
|
||||
|
||||
### 4. 蒙特卡罗π值计算 (Monte Carlo Pi)
|
||||
- 使用随机采样方法估算π值
|
||||
- 10,000,000 次迭代
|
||||
- 展示随机数生成和条件判断的性能
|
||||
|
||||
### 5. 斐波那契数列 (Fibonacci)
|
||||
- **递归方法**: fibonacci(35) - 展示递归调用的开销
|
||||
- **动态规划**: fibonacci(90) - 展示优化算法的性能差异
|
||||
|
||||
### 6. 向量点积 (Vector Dot Product)
|
||||
- 10,000,000 维向量点积计算
|
||||
- 展示大规模线性代数运算
|
||||
- 内存访问密集型操作
|
||||
|
||||
### 7. 复杂数学运算 (Complex Math)
|
||||
- sin, cos, tan, sqrt, log 等函数组合
|
||||
- 1,000,000 次迭代
|
||||
- 展示浮点运算性能
|
||||
|
||||
### 8. 内存密集型操作 (Memory Intensive)
|
||||
- 创建 1000x1000 二维数组
|
||||
- 填充和遍历大量数据
|
||||
- 展示内存分配和访问模式
|
||||
|
||||
### 9. 多线程测试 (Multi-Threading)
|
||||
- 8 个线程并行执行
|
||||
- 每个线程执行 50,000,000 次计算
|
||||
- 展示多线程性能和同步开销
|
||||
|
||||
## 如何使用
|
||||
|
||||
### 1. 编译项目
|
||||
```bash
|
||||
# 在 Visual Studio 中打开项目
|
||||
# 选择 Release 配置以获得最佳性能测试结果
|
||||
# 构建项目
|
||||
```
|
||||
|
||||
### 2. 启动 Tracy Profiler
|
||||
```bash
|
||||
# 从 Tracy 仓库的 profiler 目录运行
|
||||
# 或使用预编译的 Tracy.exe
|
||||
```
|
||||
|
||||
### 3. 运行测试程序
|
||||
```bash
|
||||
# 运行 MyProject.exe
|
||||
# Tracy Profiler 会自动连接(如果启用了 TRACY_ON_DEMAND)
|
||||
```
|
||||
|
||||
### 4. 在 Tracy 中观察
|
||||
- 查看每个函数的执行时间
|
||||
- 比较递归 vs 动态规划的性能差异
|
||||
- 观察多线程的并行执行情况
|
||||
- 分析热点函数和瓶颈
|
||||
|
||||
## Tracy 宏说明
|
||||
|
||||
- `ZoneScoped`: 自动追踪整个函数的执行时间
|
||||
- `ZoneScopedN("名称")`: 追踪代码块并指定自定义名称
|
||||
- `FrameMark`: 标记帧边界,便于区分不同的测试轮次
|
||||
|
||||
## 性能优化建议
|
||||
|
||||
根据 Tracy 的分析结果,你可以:
|
||||
|
||||
1. **识别热点**: 找出耗时最长的函数
|
||||
2. **优化算法**: 比较不同算法实现(如递归 vs 动态规划)
|
||||
3. **并行化**: 识别可以并行化的计算
|
||||
4. **缓存优化**: 观察内存访问模式,优化数据结构
|
||||
5. **减少递归**: 递归调用会带来额外开销
|
||||
|
||||
## 预期结果
|
||||
|
||||
在 Tracy Profiler 中,你应该能够看到:
|
||||
|
||||
- **矩阵乘法**: 相对较长的执行时间,CPU 密集
|
||||
- **递归斐波那契**: 大量重复的函数调用(可视化调用树)
|
||||
- **动态规划斐波那契**: 单次执行,线性时间
|
||||
- **多线程**: 8 个并行执行的线程,清晰的时间线
|
||||
- **质数计算**: 循环密集,但相对高效
|
||||
- **蒙特卡罗**: 稳定的执行时间,随机数生成开销
|
||||
|
||||
## 提示
|
||||
|
||||
- 使用 Release 配置编译可以获得更接近实际应用的性能数据
|
||||
- 多次运行测试可以在 Tracy 中观察性能的一致性
|
||||
- 尝试修改参数(矩阵大小、迭代次数等)观察性能变化
|
||||
- 使用 Tracy 的统计功能分析函数调用次数和平均执行时间
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@ vector<vector<double>> matrixMultiply(const vector<vector<double>>& A, const vec
|
||||
for (size_t j = 0; j < m; j++) {
|
||||
for (size_t k = 0; k < p; k++) {
|
||||
result[i][j] += A[i][k] * B[k][j];
|
||||
TracyPlot("matrixMultiply", result[i][j]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -46,6 +47,7 @@ vector<vector<double>> generateRandomMatrix(size_t rows, size_t cols) {
|
||||
for (size_t i = 0; i < rows; i++) {
|
||||
for (size_t j = 0; j < cols; j++) {
|
||||
matrix[i][j] = dis(gen);
|
||||
TracyPlot("generateRandomMatrix", matrix[i][j]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,7 +70,9 @@ void quickSort(vector<int>& arr, int low, int high) {
|
||||
}
|
||||
swap(arr[i + 1], arr[high]);
|
||||
int pi = i + 1;
|
||||
|
||||
|
||||
TracyPlot("quickSort.low", (int64_t)low);
|
||||
TracyPlot("quickSort.high", (int64_t)high);
|
||||
quickSort(arr, low, pi - 1);
|
||||
quickSort(arr, pi + 1, high);
|
||||
}
|
||||
@@ -88,6 +92,7 @@ vector<int> sieveOfEratosthenes(int n) {
|
||||
primes.push_back(i);
|
||||
for (int j = i * 2; j <= n; j += i) {
|
||||
isPrime[j] = false;
|
||||
TracyPlot("sieveOfEratosthenes", (isPrime[j] ? 1.0 : 0.0));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -108,7 +113,8 @@ double calculatePi(int iterations) {
|
||||
for (int i = 0; i < iterations; i++) {
|
||||
double x = dis(gen);
|
||||
double y = dis(gen);
|
||||
|
||||
|
||||
TracyPlot("calculatePi", (x * x + y * y));
|
||||
if (x * x + y * y <= 1.0) {
|
||||
insideCircle++;
|
||||
}
|
||||
@@ -120,6 +126,7 @@ double calculatePi(int iterations) {
|
||||
// 斐波那契数列(递归)
|
||||
long long fibonacci(int n) {
|
||||
ZoneScoped;
|
||||
TracyPlot("fibonacci", (int64_t)n);
|
||||
|
||||
if (n <= 1) return n;
|
||||
return fibonacci(n - 1) + fibonacci(n - 2);
|
||||
@@ -149,6 +156,7 @@ double dotProduct(const vector<double>& a, const vector<double>& b) {
|
||||
double result = 0.0;
|
||||
for (size_t i = 0; i < a.size(); i++) {
|
||||
result += a[i] * b[i];
|
||||
TracyPlot("dotProduct", result);
|
||||
}
|
||||
|
||||
return result;
|
||||
@@ -161,6 +169,7 @@ void complexMathOperations(int iterations) {
|
||||
double sum = 0.0;
|
||||
for (int i = 1; i <= iterations; i++) {
|
||||
sum += sin(i) * cos(i) + tan(i / 100.0) + sqrt(i) + log(i);
|
||||
TracyPlot("complexMathOperations", sum);
|
||||
}
|
||||
|
||||
cout << "复杂数学计算结果: " << sum << endl;
|
||||
@@ -175,7 +184,7 @@ void memoryIntensiveOperation(size_t size) {
|
||||
// 填充数据
|
||||
for (size_t i = 0; i < size; i++) {
|
||||
for (size_t j = 0; j < size; j++) {
|
||||
bigArray[i][j] = i * j;
|
||||
bigArray[i][j] = static_cast<int>(i * j);
|
||||
}
|
||||
}
|
||||
|
||||
BIN
tracy-0.13.0-cli/tracy-capture.exe
Normal file
BIN
tracy-0.13.0-cli/tracy-capture.exe
Normal file
Binary file not shown.
BIN
tracy-0.13.0-cli/tracy-csvexport.exe
Normal file
BIN
tracy-0.13.0-cli/tracy-csvexport.exe
Normal file
Binary file not shown.
BIN
tracy-0.13.0-cli/tracy-import-chrome.exe
Normal file
BIN
tracy-0.13.0-cli/tracy-import-chrome.exe
Normal file
Binary file not shown.
BIN
tracy-0.13.0-cli/tracy-import-fuchsia.exe
Normal file
BIN
tracy-0.13.0-cli/tracy-import-fuchsia.exe
Normal file
Binary file not shown.
BIN
tracy-0.13.0-cli/tracy-profiler.exe
Normal file
BIN
tracy-0.13.0-cli/tracy-profiler.exe
Normal file
Binary file not shown.
BIN
tracy-0.13.0-cli/tracy-update.exe
Normal file
BIN
tracy-0.13.0-cli/tracy-update.exe
Normal file
Binary file not shown.
BIN
tracy-0.13.0.zip
BIN
tracy-0.13.0.zip
Binary file not shown.
@@ -11,37 +11,37 @@ set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
# 配置选项
|
||||
# ============================================
|
||||
|
||||
option(TRACY_ENABLE "启用 Tracy 性能分析" ON)
|
||||
option(TRACY_ON_DEMAND "Tracy 按需分析模式" ON)
|
||||
option(TRACY_NO_EXIT "Tracy 不在退出时断开连接" OFF)
|
||||
option(TRACY_NO_BROADCAST "Tracy 不广播发现消息" OFF)
|
||||
option(TRACY_ONLY_LOCALHOST "Tracy 仅允许本地连接" OFF)
|
||||
option(IS_TRACY_ENABLE "启用 Tracy 性能分析" ON)
|
||||
option(IS_TRACY_ON_DEMAND "Tracy 按需分析模式" ON)
|
||||
option(IS_TRACY_NO_EXIT "Tracy 不在退出时断开连接" OFF)
|
||||
option(IS_TRACY_NO_BROADCAST "Tracy 不广播发现消息" OFF)
|
||||
option(IS_TRACY_ONLY_LOCALHOST "Tracy 仅允许本地连接" OFF)
|
||||
|
||||
# ============================================
|
||||
# Tracy 配置
|
||||
# ============================================
|
||||
|
||||
if(TRACY_ENABLE)
|
||||
if(IS_TRACY_ENABLE)
|
||||
add_definitions(-DTRACY_ENABLE)
|
||||
message(STATUS "Tracy 性能分析: 启用")
|
||||
else()
|
||||
message(STATUS "Tracy 性能分析: 禁用")
|
||||
endif()
|
||||
|
||||
if(TRACY_ON_DEMAND)
|
||||
if(IS_TRACY_ON_DEMAND)
|
||||
add_definitions(-DTRACY_ON_DEMAND)
|
||||
message(STATUS "Tracy 按需模式: 启用")
|
||||
endif()
|
||||
|
||||
if(TRACY_NO_EXIT)
|
||||
if(IS_TRACY_NO_EXIT)
|
||||
add_definitions(-DTRACY_NO_EXIT)
|
||||
endif()
|
||||
|
||||
if(TRACY_NO_BROADCAST)
|
||||
if(IS_TRACY_NO_BROADCAST)
|
||||
add_definitions(-DTRACY_NO_BROADCAST)
|
||||
endif()
|
||||
|
||||
if(TRACY_ONLY_LOCALHOST)
|
||||
if(IS_TRACY_ONLY_LOCALHOST)
|
||||
add_definitions(-DTRACY_ONLY_LOCALHOST)
|
||||
endif()
|
||||
|
||||
@@ -251,8 +251,8 @@ message(STATUS "项目版本: ${PROJECT_VERSION}")
|
||||
message(STATUS "C++ 标准: ${CMAKE_CXX_STANDARD}")
|
||||
message(STATUS "构建类型: ${CMAKE_BUILD_TYPE}")
|
||||
message(STATUS "编译器: ${CMAKE_CXX_COMPILER_ID}")
|
||||
message(STATUS "Tracy 启用: ${TRACY_ENABLE}")
|
||||
message(STATUS "Tracy 按需模式: ${TRACY_ON_DEMAND}")
|
||||
message(STATUS "Tracy 启用: ${IS_TRACY_ENABLE}")
|
||||
message(STATUS "Tracy 按需模式: ${IS_TRACY_ON_DEMAND}")
|
||||
message(STATUS "========================================")
|
||||
|
||||
# ============================================
|
||||
|
||||
@@ -1,494 +0,0 @@
|
||||
# Tracy Unity 集成快速开始指南
|
||||
|
||||
本指南将帮助你快速将 Tracy 性能分析器集成到 Unity 项目中。
|
||||
|
||||
---
|
||||
|
||||
## 🚀 快速开始(5 分钟集成)
|
||||
|
||||
### 步骤 1: 准备 Tracy
|
||||
|
||||
1. 克隆或下载 Tracy 仓库:
|
||||
```bash
|
||||
git clone https://github.com/wolfpld/tracy.git
|
||||
```
|
||||
|
||||
2. (可选)编译 Tracy Profiler 工具:
|
||||
```bash
|
||||
cd tracy/profiler
|
||||
# Windows: 使用 Visual Studio 打开并编译
|
||||
# macOS/Linux:
|
||||
cmake -B build -DCMAKE_BUILD_TYPE=Release
|
||||
cmake --build build
|
||||
```
|
||||
|
||||
### 步骤 2: 编译 Unity Plugin
|
||||
|
||||
#### Windows (使用 CMake + Visual Studio)
|
||||
|
||||
```powershell
|
||||
# 在 unity_examples 目录下
|
||||
mkdir build
|
||||
cd build
|
||||
|
||||
# 配置(修改 TRACY_ROOT 路径指向你的 tracy 目录)
|
||||
cmake .. -G "Visual Studio 17 2022" -A x64 ^
|
||||
-DTRACY_ROOT="D:/path/to/tracy" ^
|
||||
-DTRACY_ENABLE=ON ^
|
||||
-DTRACY_ON_DEMAND=ON
|
||||
|
||||
# 编译
|
||||
cmake --build . --config Release
|
||||
```
|
||||
|
||||
编译完成后,DLL 文件在 `build/Unity/Plugins/x86_64/UnityTracyPlugin.dll`
|
||||
|
||||
#### macOS
|
||||
|
||||
```bash
|
||||
# 在 unity_examples 目录下
|
||||
mkdir build && cd build
|
||||
|
||||
# 配置
|
||||
cmake .. \
|
||||
-DCMAKE_BUILD_TYPE=Release \
|
||||
-DTRACY_ROOT="/path/to/tracy" \
|
||||
-DTRACY_ENABLE=ON \
|
||||
-DTRACY_ON_DEMAND=ON
|
||||
|
||||
# 编译
|
||||
make -j8
|
||||
```
|
||||
|
||||
编译完成后,动态库在 `build/Unity/Plugins/macOS/UnityTracyPlugin.dylib`
|
||||
|
||||
#### Linux
|
||||
|
||||
```bash
|
||||
# 在 unity_examples 目录下
|
||||
mkdir build && cd build
|
||||
|
||||
# 配置
|
||||
cmake .. \
|
||||
-DCMAKE_BUILD_TYPE=Release \
|
||||
-DTRACY_ROOT="/path/to/tracy" \
|
||||
-DTRACY_ENABLE=ON \
|
||||
-DTRACY_ON_DEMAND=ON
|
||||
|
||||
# 编译
|
||||
make -j8
|
||||
```
|
||||
|
||||
编译完成后,动态库在 `build/Unity/Plugins/Linux/x86_64/UnityTracyPlugin.so`
|
||||
|
||||
### 步骤 3: 集成到 Unity 项目
|
||||
|
||||
1. **复制 Plugin 文件**
|
||||
|
||||
将编译好的 Plugin 复制到 Unity 项目:
|
||||
|
||||
```
|
||||
YourUnityProject/
|
||||
└── Assets/
|
||||
└── Plugins/
|
||||
├── x86_64/
|
||||
│ └── UnityTracyPlugin.dll # Windows
|
||||
├── macOS/
|
||||
│ └── UnityTracyPlugin.dylib # macOS
|
||||
└── Linux/
|
||||
└── x86_64/
|
||||
└── UnityTracyPlugin.so # Linux
|
||||
```
|
||||
|
||||
2. **复制 C# 脚本**
|
||||
|
||||
将以下文件复制到 Unity 项目:
|
||||
|
||||
```
|
||||
YourUnityProject/
|
||||
└── Assets/
|
||||
└── Scripts/
|
||||
└── Tracy/
|
||||
├── TracyWrapper.cs # Tracy C# API
|
||||
├── TracyManager.cs # Tracy 管理器
|
||||
└── TracyExamples.cs # 使用示例(可选)
|
||||
```
|
||||
|
||||
3. **配置 Plugin 导入设置**
|
||||
|
||||
在 Unity Editor 中:
|
||||
- 选择 `UnityTracyPlugin.dll`(或 .dylib/.so)
|
||||
- 在 Inspector 中设置平台:
|
||||
- Windows: 勾选 `x86_64`
|
||||
- macOS: 勾选 `macOS`
|
||||
- Linux: 勾选 `Linux x86_64`
|
||||
|
||||
### 步骤 4: 在场景中使用
|
||||
|
||||
1. **添加 TracyManager**
|
||||
|
||||
在你的主场景中:
|
||||
- 创建空 GameObject,命名为 "TracyManager"
|
||||
- 添加 `TracyManager` 组件
|
||||
- 在 Inspector 中配置选项
|
||||
|
||||
2. **在代码中使用 Tracy**
|
||||
|
||||
```csharp
|
||||
using UnityEngine;
|
||||
using TracyProfiler;
|
||||
|
||||
public class MyGameScript : MonoBehaviour
|
||||
{
|
||||
void Update()
|
||||
{
|
||||
// 方式 1: 使用 using 语句(推荐)
|
||||
using (Tracy.Zone("MyGameScript.Update"))
|
||||
{
|
||||
DoSomething();
|
||||
}
|
||||
|
||||
// 方式 2: 手动开始/结束
|
||||
Tracy.BeginZone("CustomZone");
|
||||
DoSomethingElse();
|
||||
Tracy.EndZone();
|
||||
|
||||
// 绘制数值
|
||||
Tracy.Plot("Enemy Count", enemyCount);
|
||||
|
||||
// 发送消息
|
||||
if (playerDied)
|
||||
{
|
||||
Tracy.Message("Player died");
|
||||
}
|
||||
}
|
||||
|
||||
void DoSomething()
|
||||
{
|
||||
using (Tracy.Zone("DoSomething"))
|
||||
{
|
||||
// 你的代码
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 步骤 5: 启动 Tracy Profiler 并连接
|
||||
|
||||
1. **启动 Tracy Profiler**
|
||||
|
||||
```bash
|
||||
# Windows
|
||||
Tracy.exe
|
||||
|
||||
# macOS/Linux
|
||||
./Tracy
|
||||
```
|
||||
|
||||
2. **运行 Unity 游戏**
|
||||
|
||||
在 Unity Editor 中按 Play,或运行构建的可执行文件。
|
||||
|
||||
3. **连接到 Tracy**
|
||||
|
||||
Tracy Profiler 会自动发现本地网络中的 Tracy 客户端,点击连接即可开始分析。
|
||||
|
||||
---
|
||||
|
||||
## 📊 使用 Tracy 分析性能
|
||||
|
||||
### 查看性能数据
|
||||
|
||||
Tracy Profiler 界面主要区域:
|
||||
|
||||
1. **时间线视图**
|
||||
- 显示所有 Zone 的执行时间
|
||||
- 颜色表示不同的调用栈深度
|
||||
- 可以缩放和平移
|
||||
|
||||
2. **统计视图**
|
||||
- 函数调用次数
|
||||
- 总耗时、平均耗时、最小/最大耗时
|
||||
- 排序和筛选功能
|
||||
|
||||
3. **帧视图**
|
||||
- 查看每帧的性能
|
||||
- 识别帧率波动
|
||||
- 帧时间分布
|
||||
|
||||
4. **Plot 视图**
|
||||
- 查看 `Tracy.Plot()` 绘制的数值曲线
|
||||
- 实时监控变量变化
|
||||
|
||||
### 常用快捷键
|
||||
|
||||
- `鼠标滚轮`: 缩放时间线
|
||||
- `鼠标中键拖拽`: 平移时间线
|
||||
- `鼠标左键`: 选择 Zone 查看详情
|
||||
- `Ctrl + F`: 搜索函数
|
||||
- `Ctrl + Z`: 放大到选中的 Zone
|
||||
|
||||
---
|
||||
|
||||
## 🔧 常见问题排查
|
||||
|
||||
### 问题 1: DLL 加载失败
|
||||
|
||||
**错误信息**: `DllNotFoundException: UnityTracyPlugin`
|
||||
|
||||
**解决方案**:
|
||||
1. 确认 DLL 文件在正确的目录
|
||||
2. 检查 Plugin Import Settings 的平台配置
|
||||
3. 确认 DLL 架构与 Unity 项目匹配(x64/x86)
|
||||
4. Windows: 检查是否缺少 `vcruntime140.dll`(安装 Visual C++ Redistributable)
|
||||
|
||||
### 问题 2: Tracy Profiler 无法连接
|
||||
|
||||
**症状**: Tracy Profiler 中看不到 Unity 应用
|
||||
|
||||
**解决方案**:
|
||||
1. 确认防火墙允许 TCP 端口 8086
|
||||
2. 检查 `TRACY_ON_DEMAND` 宏是否正确定义
|
||||
3. 确认 `Tracy.Initialize()` 已被调用
|
||||
4. 检查 Unity Console 是否有 Tracy 初始化消息
|
||||
|
||||
```csharp
|
||||
// 在 Unity Console 应该看到:
|
||||
// [Tracy] 性能分析器已初始化
|
||||
```
|
||||
|
||||
### 问题 3: 性能数据不显示
|
||||
|
||||
**症状**: Tracy 已连接,但看不到任何 Zone
|
||||
|
||||
**解决方案**:
|
||||
1. 确认代码中使用了 `Tracy.Zone()` 或 `ZoneScoped`
|
||||
2. 确认 `Tracy.MarkFrame()` 在每帧被调用
|
||||
3. 检查是否定义了 `TRACY_ENABLE` 编译符号
|
||||
4. 在 Unity Editor 中,确认 Tracy Manager 的 "Enable On Start" 已勾选
|
||||
|
||||
### 问题 4: 编译错误
|
||||
|
||||
**常见编译错误**:
|
||||
|
||||
1. **找不到 Tracy.hpp**
|
||||
```
|
||||
fatal error: tracy/Tracy.hpp: No such file or directory
|
||||
```
|
||||
解决: 检查 `TRACY_ROOT` 路径是否正确
|
||||
|
||||
2. **链接错误 (Windows)**
|
||||
```
|
||||
error LNK2019: unresolved external symbol
|
||||
```
|
||||
解决: 确认链接了 `ws2_32.lib` 和 `dbghelp.lib`
|
||||
|
||||
3. **链接错误 (Linux)**
|
||||
```
|
||||
undefined reference to `pthread_create'
|
||||
```
|
||||
解决: 添加 `-lpthread -ldl` 链接选项
|
||||
|
||||
### 问题 5: Android/iOS 构建问题
|
||||
|
||||
**Android**:
|
||||
1. 使用 Android NDK 编译
|
||||
2. 确保为所有需要的 ABI 编译(armeabi-v7a, arm64-v8a)
|
||||
3. 将 `.so` 文件放在 `Assets/Plugins/Android/libs/{ABI}/`
|
||||
|
||||
**iOS**:
|
||||
1. 编译为静态库(.a)
|
||||
2. 在 Unity Build Settings 中设置 "Target SDK" 为 "Device SDK"
|
||||
3. 确保代码签名正确
|
||||
|
||||
---
|
||||
|
||||
## 🎯 最佳实践
|
||||
|
||||
### 1. Zone 命名规范
|
||||
|
||||
```csharp
|
||||
// ✅ 好的命名 - 清晰、描述性
|
||||
using (Tracy.Zone("PlayerController.Move"))
|
||||
using (Tracy.Zone("AI.UpdatePathfinding"))
|
||||
using (Tracy.Zone("Render.DrawTerrain"))
|
||||
|
||||
// ❌ 不好的命名 - 模糊、无意义
|
||||
using (Tracy.Zone("Function1"))
|
||||
using (Tracy.Zone("Update"))
|
||||
using (Tracy.Zone("Test"))
|
||||
```
|
||||
|
||||
### 2. 适度使用 Zone
|
||||
|
||||
```csharp
|
||||
void Update()
|
||||
{
|
||||
// ✅ 追踪主要的逻辑块
|
||||
using (Tracy.Zone("Update"))
|
||||
{
|
||||
using (Tracy.Zone("ProcessInput"))
|
||||
{
|
||||
ProcessInput(); // 追踪大块逻辑
|
||||
}
|
||||
|
||||
UpdateGameLogic(); // 内部有自己的 Zone
|
||||
}
|
||||
}
|
||||
|
||||
// ❌ 过度追踪会增加开销
|
||||
void BadExample()
|
||||
{
|
||||
for (int i = 0; i < 10000; i++)
|
||||
{
|
||||
using (Tracy.Zone($"Iteration {i}")) // 太多 Zone!
|
||||
{
|
||||
DoSomething();
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 3. 使用条件编译
|
||||
|
||||
```csharp
|
||||
// 在生产构建中禁用细粒度追踪
|
||||
#if TRACY_ENABLE
|
||||
using (Tracy.Zone("DetailedAnalysis"))
|
||||
{
|
||||
// 详细的性能分析代码
|
||||
}
|
||||
#endif
|
||||
```
|
||||
|
||||
### 4. 监控关键指标
|
||||
|
||||
```csharp
|
||||
void LateUpdate()
|
||||
{
|
||||
// 监控帧率
|
||||
Tracy.Plot("FPS", 1.0f / Time.deltaTime);
|
||||
|
||||
// 监控内存
|
||||
Tracy.Plot("Memory (MB)", GC.GetTotalMemory(false) / 1024.0 / 1024.0);
|
||||
|
||||
// 监控对象计数
|
||||
Tracy.Plot("Enemy Count", enemies.Count);
|
||||
Tracy.Plot("Active Particles", particleSystem.particleCount);
|
||||
|
||||
// 监控物理
|
||||
Tracy.Plot("Rigidbodies", FindObjectsOfType<Rigidbody>().Length);
|
||||
}
|
||||
```
|
||||
|
||||
### 5. 多线程命名
|
||||
|
||||
```csharp
|
||||
using System.Threading;
|
||||
|
||||
void WorkerThread()
|
||||
{
|
||||
Tracy.SetThreadName("Worker Thread");
|
||||
|
||||
while (running)
|
||||
{
|
||||
using (Tracy.Zone("WorkerThread.Process"))
|
||||
{
|
||||
ProcessData();
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📚 进阶主题
|
||||
|
||||
### 自定义构建配置
|
||||
|
||||
在 Unity 项目中创建 `link.xml` 防止代码剥离:
|
||||
|
||||
```xml
|
||||
<linker>
|
||||
<assembly fullname="Assembly-CSharp">
|
||||
<namespace fullname="TracyProfiler" preserve="all"/>
|
||||
</assembly>
|
||||
</linker>
|
||||
```
|
||||
|
||||
### 持久化性能数据
|
||||
|
||||
Tracy 支持保存性能数据到文件:
|
||||
|
||||
1. 在 Tracy Profiler 中,点击 "Save trace"
|
||||
2. 选择保存位置(.tracy 文件)
|
||||
3. 之后可以用 Tracy Profiler 打开查看
|
||||
|
||||
### 集成到 CI/CD
|
||||
|
||||
可以在自动化测试中使用 Tracy:
|
||||
|
||||
```csharp
|
||||
public class PerformanceTest
|
||||
{
|
||||
[Test]
|
||||
public void TestPerformance()
|
||||
{
|
||||
Tracy.Initialize();
|
||||
|
||||
using (Tracy.Zone("PerformanceTest"))
|
||||
{
|
||||
// 运行性能测试
|
||||
RunGameLoop(100); // 运行 100 帧
|
||||
}
|
||||
|
||||
Tracy.Shutdown();
|
||||
|
||||
// 分析结果...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔗 资源链接
|
||||
|
||||
- [Tracy 官方仓库](https://github.com/wolfpld/tracy)
|
||||
- [Tracy 官方手册](https://github.com/wolfpld/tracy/releases/latest/download/tracy.pdf)
|
||||
- [Unity Native Plugin 文档](https://docs.unity3d.com/Manual/NativePlugins.html)
|
||||
- 本项目的完整文档: `UNITY_INTEGRATION_GUIDE.md`
|
||||
|
||||
---
|
||||
|
||||
## 💡 技巧和提示
|
||||
|
||||
1. **使用 Release 构建进行性能测试**
|
||||
- Debug 构建会有大量额外开销
|
||||
- 在 Unity 中创建专门的 "Profiling" 构建配置
|
||||
|
||||
2. **关闭 V-Sync 测试真实性能**
|
||||
- V-Sync 会限制帧率
|
||||
- 在 Project Settings > Quality 中关闭
|
||||
|
||||
3. **使用 Tracy 的统计功能**
|
||||
- 查看函数调用次数
|
||||
- 识别被频繁调用的函数
|
||||
|
||||
4. **比较不同实现**
|
||||
- 使用 Tracy 比较算法性能
|
||||
- A/B 测试优化效果
|
||||
|
||||
5. **定期保存 Trace 文件**
|
||||
- 记录性能基准
|
||||
- 跟踪性能变化趋势
|
||||
|
||||
---
|
||||
|
||||
## 🎉 完成!
|
||||
|
||||
现在你已经成功将 Tracy 集成到 Unity 项目中了!
|
||||
|
||||
开始使用 Tracy 分析你的游戏性能,找出瓶颈,优化代码吧!
|
||||
|
||||
如有问题,请参考完整文档 `UNITY_INTEGRATION_GUIDE.md` 或访问 Tracy 官方仓库。
|
||||
|
||||
@@ -1,484 +0,0 @@
|
||||
# Tracy Unity 集成示例
|
||||
|
||||
本目录包含将 Tracy 性能分析器集成到 Unity 项目的完整示例和工具。
|
||||
|
||||
## 📁 文件结构
|
||||
|
||||
```
|
||||
unity_examples/
|
||||
├── README.md # 本文件 - 项目概述
|
||||
├── QUICKSTART.md # 5分钟快速开始指南 ⭐ 从这里开始!
|
||||
├── CMakeLists.txt # CMake 构建配置
|
||||
├── SimplifiedPlugin.cpp # Tracy Unity Plugin C++ 实现
|
||||
├── TracyWrapper.cs # Tracy C# API 封装
|
||||
├── TracyManager.cs # Tracy 管理器组件
|
||||
└── TracyExamples.cs # 使用示例和最佳实践
|
||||
```
|
||||
|
||||
## 🚀 快速开始
|
||||
|
||||
### 新手用户
|
||||
|
||||
如果你是第一次使用,请按以下顺序阅读:
|
||||
|
||||
1. **[QUICKSTART.md](QUICKSTART.md)** - 5分钟快速集成指南
|
||||
2. **[TracyExamples.cs](TracyExamples.cs)** - 查看代码示例
|
||||
3. **[../UNITY_INTEGRATION_GUIDE.md](../UNITY_INTEGRATION_GUIDE.md)** - 完整的集成文档
|
||||
|
||||
### 有经验的用户
|
||||
|
||||
快速集成步骤:
|
||||
|
||||
```bash
|
||||
# 1. 编译 Plugin
|
||||
mkdir build && cd build
|
||||
cmake .. -DTRACY_ROOT="/path/to/tracy" -DCMAKE_BUILD_TYPE=Release
|
||||
cmake --build . --config Release
|
||||
|
||||
# 2. 复制文件到 Unity 项目
|
||||
cp build/Unity/Plugins/* YourUnityProject/Assets/Plugins/
|
||||
cp *.cs YourUnityProject/Assets/Scripts/Tracy/
|
||||
|
||||
# 3. 在 Unity 场景中添加 TracyManager 组件
|
||||
|
||||
# 4. 运行 Tracy Profiler 并连接
|
||||
```
|
||||
|
||||
## 📦 文件说明
|
||||
|
||||
### C++ Plugin 相关
|
||||
|
||||
#### `SimplifiedPlugin.cpp`
|
||||
Tracy Unity Native Plugin 的 C++ 实现。
|
||||
|
||||
**主要功能**:
|
||||
- 初始化/关闭 Tracy
|
||||
- 创建性能追踪 Zone
|
||||
- 绘制实时数值
|
||||
- 发送消息和日志
|
||||
- 线程命名
|
||||
|
||||
**导出函数**:
|
||||
```cpp
|
||||
TracyInit() // 初始化
|
||||
TracyShutdown() // 关闭
|
||||
TracyFrameMark() // 标记帧边界
|
||||
TracyZoneBegin(name) // 开始 Zone
|
||||
TracyZoneEnd() // 结束 Zone
|
||||
TracyPlotValue(name, v) // 绘制数值
|
||||
TracyMessage(msg) // 发送消息
|
||||
TracySetThreadName(name) // 设置线程名
|
||||
```
|
||||
|
||||
**编译要求**:
|
||||
- C++17
|
||||
- Tracy 源代码
|
||||
- Windows: Visual Studio 2019+
|
||||
- macOS: Xcode 12+
|
||||
- Linux: GCC 9+ 或 Clang 10+
|
||||
|
||||
#### `CMakeLists.txt`
|
||||
跨平台 CMake 构建配置。
|
||||
|
||||
**支持平台**:
|
||||
- ✅ Windows (x64)
|
||||
- ✅ macOS (Intel/Apple Silicon)
|
||||
- ✅ Linux (x64)
|
||||
- ✅ Android (armeabi-v7a, arm64-v8a)
|
||||
- ✅ iOS (arm64)
|
||||
|
||||
**配置选项**:
|
||||
```cmake
|
||||
-DTRACY_ENABLE=ON # 启用 Tracy
|
||||
-DTRACY_ON_DEMAND=ON # 按需分析模式
|
||||
-DTRACY_ROOT=path # Tracy 根目录
|
||||
```
|
||||
|
||||
### C# 脚本相关
|
||||
|
||||
#### `TracyWrapper.cs`
|
||||
Tracy 的 C# API 封装,提供简洁易用的接口。
|
||||
|
||||
**核心 API**:
|
||||
```csharp
|
||||
// 初始化
|
||||
Tracy.Initialize()
|
||||
|
||||
// 性能追踪 (推荐使用 using 语句)
|
||||
using (Tracy.Zone("FunctionName"))
|
||||
{
|
||||
// 要追踪的代码
|
||||
}
|
||||
|
||||
// 手动管理 Zone
|
||||
Tracy.BeginZone("CustomZone")
|
||||
// ... 代码 ...
|
||||
Tracy.EndZone()
|
||||
|
||||
// 绘制实时数值
|
||||
Tracy.Plot("FPS", fps)
|
||||
Tracy.Plot("Memory", memoryMB)
|
||||
|
||||
// 发送消息
|
||||
Tracy.Message("重要事件发生")
|
||||
|
||||
// 设置线程名
|
||||
Tracy.SetThreadName("Worker Thread")
|
||||
|
||||
// 标记帧边界
|
||||
Tracy.MarkFrame()
|
||||
```
|
||||
|
||||
**特性**:
|
||||
- 使用 `IDisposable` 自动管理 Zone 生命周期
|
||||
- 条件编译支持(`TRACY_ENABLE`)
|
||||
- 零开销(禁用时)
|
||||
- 线程安全
|
||||
|
||||
#### `TracyManager.cs`
|
||||
Unity 组件,负责 Tracy 的初始化和自动化监控。
|
||||
|
||||
**功能**:
|
||||
- 自动初始化 Tracy
|
||||
- 每帧自动标记帧边界
|
||||
- 自动监控系统指标:
|
||||
- 帧率 (FPS)
|
||||
- 帧时间
|
||||
- 内存使用
|
||||
- 渲染统计
|
||||
- 物理对象数量
|
||||
|
||||
**使用方法**:
|
||||
1. 在场景中创建空 GameObject
|
||||
2. 添加 `TracyManager` 组件
|
||||
3. 配置 Inspector 中的选项
|
||||
4. 运行游戏
|
||||
|
||||
**Inspector 选项**:
|
||||
- `Enable On Start`: 启动时自动初始化
|
||||
- `Mark Frames`: 每帧自动标记
|
||||
- `Monitor Frame Rate`: 监控帧率
|
||||
- `Monitor Memory`: 监控内存
|
||||
- `Monitor Rendering`: 监控渲染
|
||||
- `Monitor Physics`: 监控物理
|
||||
|
||||
#### `TracyExamples.cs`
|
||||
完整的使用示例和最佳实践。
|
||||
|
||||
**包含示例**:
|
||||
1. ✅ 基础 Zone 使用
|
||||
2. ✅ 计算密集型操作追踪
|
||||
3. ✅ 重度计算测试
|
||||
4. ✅ 对象池管理
|
||||
5. ✅ 协程性能追踪
|
||||
6. ✅ 自定义数据绘制
|
||||
7. ✅ 条件性能追踪
|
||||
|
||||
**交互功能**:
|
||||
- 按 `Space` 键: 执行重度计算
|
||||
- 按 `R` 键: 重置对象池
|
||||
- 按 `T` 键: 运行性能测试
|
||||
|
||||
## 🎯 使用场景
|
||||
|
||||
### 1. 游戏开发性能优化
|
||||
|
||||
```csharp
|
||||
public class GameController : MonoBehaviour
|
||||
{
|
||||
void Update()
|
||||
{
|
||||
using (Tracy.Zone("GameController.Update"))
|
||||
{
|
||||
using (Tracy.Zone("Update AI"))
|
||||
{
|
||||
UpdateAI();
|
||||
}
|
||||
|
||||
using (Tracy.Zone("Update Physics"))
|
||||
{
|
||||
UpdatePhysics();
|
||||
}
|
||||
|
||||
using (Tracy.Zone("Update Rendering"))
|
||||
{
|
||||
UpdateRendering();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 2. 资源加载分析
|
||||
|
||||
```csharp
|
||||
IEnumerator LoadScene()
|
||||
{
|
||||
using (Tracy.Zone("Load Scene"))
|
||||
{
|
||||
using (Tracy.Zone("Load Assets"))
|
||||
{
|
||||
yield return LoadAssets();
|
||||
}
|
||||
|
||||
using (Tracy.Zone("Initialize Scene"))
|
||||
{
|
||||
InitializeScene();
|
||||
}
|
||||
|
||||
Tracy.Message("Scene loaded successfully");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 3. AI 系统性能追踪
|
||||
|
||||
```csharp
|
||||
public class AIManager : MonoBehaviour
|
||||
{
|
||||
void Update()
|
||||
{
|
||||
using (Tracy.Zone("AI Manager"))
|
||||
{
|
||||
foreach (var agent in agents)
|
||||
{
|
||||
using (Tracy.Zone($"AI Agent {agent.id}"))
|
||||
{
|
||||
agent.UpdateBehavior();
|
||||
}
|
||||
}
|
||||
|
||||
Tracy.Plot("Active AI Agents", agents.Count);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 4. 网络同步分析
|
||||
|
||||
```csharp
|
||||
void OnNetworkUpdate()
|
||||
{
|
||||
using (Tracy.Zone("Network Update"))
|
||||
{
|
||||
using (Tracy.Zone("Receive Packets"))
|
||||
{
|
||||
ReceivePackets();
|
||||
}
|
||||
|
||||
using (Tracy.Zone("Process Messages"))
|
||||
{
|
||||
ProcessMessages();
|
||||
}
|
||||
|
||||
using (Tracy.Zone("Send Updates"))
|
||||
{
|
||||
SendUpdates();
|
||||
}
|
||||
|
||||
Tracy.Plot("Network Latency (ms)", latency);
|
||||
Tracy.Plot("Packet Loss (%)", packetLoss);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 5. 渲染管线优化
|
||||
|
||||
```csharp
|
||||
void OnPreRender()
|
||||
{
|
||||
using (Tracy.Zone("Pre-Render"))
|
||||
{
|
||||
using (Tracy.Zone("Culling"))
|
||||
{
|
||||
PerformCulling();
|
||||
}
|
||||
|
||||
using (Tracy.Zone("Sort Render Queue"))
|
||||
{
|
||||
SortRenderQueue();
|
||||
}
|
||||
|
||||
Tracy.Plot("Visible Objects", visibleCount);
|
||||
Tracy.Plot("Draw Calls", drawCalls);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 🔧 平台特定说明
|
||||
|
||||
### Windows
|
||||
|
||||
**依赖**:
|
||||
- Visual Studio 2019 或更高版本
|
||||
- Windows SDK
|
||||
- vcruntime140.dll (Visual C++ Redistributable)
|
||||
|
||||
**编译**:
|
||||
```powershell
|
||||
cmake -B build -G "Visual Studio 17 2022" -A x64
|
||||
cmake --build build --config Release
|
||||
```
|
||||
|
||||
**输出**: `build/Unity/Plugins/x86_64/UnityTracyPlugin.dll`
|
||||
|
||||
### macOS
|
||||
|
||||
**依赖**:
|
||||
- Xcode Command Line Tools
|
||||
- CMake 3.15+
|
||||
|
||||
**编译**:
|
||||
```bash
|
||||
cmake -B build -DCMAKE_BUILD_TYPE=Release
|
||||
cmake --build build
|
||||
```
|
||||
|
||||
**输出**: `build/Unity/Plugins/macOS/UnityTracyPlugin.dylib`
|
||||
|
||||
**注意**: Apple Silicon (M1/M2) 和 Intel 需要分别编译
|
||||
|
||||
### Linux
|
||||
|
||||
**依赖**:
|
||||
- GCC 9+ 或 Clang 10+
|
||||
- pthread, dl
|
||||
|
||||
**编译**:
|
||||
```bash
|
||||
cmake -B build -DCMAKE_BUILD_TYPE=Release
|
||||
cmake --build build
|
||||
```
|
||||
|
||||
**输出**: `build/Unity/Plugins/Linux/x86_64/UnityTracyPlugin.so`
|
||||
|
||||
### Android
|
||||
|
||||
**依赖**:
|
||||
- Android NDK r21+
|
||||
- CMake 3.15+
|
||||
|
||||
**编译**:
|
||||
```bash
|
||||
# ARM64
|
||||
cmake -B build-android-arm64 \
|
||||
-DCMAKE_TOOLCHAIN_FILE=$ANDROID_NDK/build/cmake/android.toolchain.cmake \
|
||||
-DANDROID_ABI=arm64-v8a \
|
||||
-DANDROID_PLATFORM=android-21
|
||||
|
||||
# ARMv7
|
||||
cmake -B build-android-armv7 \
|
||||
-DCMAKE_TOOLCHAIN_FILE=$ANDROID_NDK/build/cmake/android.toolchain.cmake \
|
||||
-DANDROID_ABI=armeabi-v7a \
|
||||
-DANDROID_PLATFORM=android-21
|
||||
```
|
||||
|
||||
### iOS
|
||||
|
||||
**依赖**:
|
||||
- Xcode 12+
|
||||
- iOS SDK
|
||||
|
||||
**编译**:
|
||||
```bash
|
||||
cmake -B build-ios \
|
||||
-DCMAKE_SYSTEM_NAME=iOS \
|
||||
-DCMAKE_OSX_ARCHITECTURES=arm64 \
|
||||
-DCMAKE_OSX_DEPLOYMENT_TARGET=12.0
|
||||
```
|
||||
|
||||
**注意**: iOS 需要静态库(.a)而不是动态库
|
||||
|
||||
## 📊 性能影响
|
||||
|
||||
### Tracy 开销
|
||||
|
||||
| 配置 | 每 Zone 开销 | 内存开销 | 网络带宽 |
|
||||
|------|-------------|---------|---------|
|
||||
| 禁用 (Release) | 0 ns | 0 MB | 0 |
|
||||
| 启用 (On-Demand, 未连接) | ~20 ns | ~1 MB | 0 |
|
||||
| 启用 (已连接) | ~50 ns | ~10 MB | ~1 Mbps |
|
||||
|
||||
### 建议
|
||||
|
||||
- ✅ 在 Debug/Development 构建中启用
|
||||
- ✅ 追踪主要逻辑块(毫秒级)
|
||||
- ⚠️ 避免追踪微小操作(微秒级)
|
||||
- ⚠️ 避免在紧密循环中创建 Zone
|
||||
- ❌ 不建议在 Release 构建中启用细粒度追踪
|
||||
|
||||
## 🐛 故障排除
|
||||
|
||||
### 常见问题
|
||||
|
||||
详细的故障排除指南请参考 [QUICKSTART.md](QUICKSTART.md#常见问题排查)
|
||||
|
||||
**快速检查清单**:
|
||||
|
||||
- [ ] DLL 文件在正确的 Plugins 目录
|
||||
- [ ] Plugin Import Settings 配置正确
|
||||
- [ ] Tracy Profiler 正在运行
|
||||
- [ ] 防火墙允许端口 8086
|
||||
- [ ] `Tracy.Initialize()` 已被调用
|
||||
- [ ] Unity Console 显示初始化消息
|
||||
- [ ] 代码中使用了 `Tracy.Zone()` 或 `ZoneScoped`
|
||||
- [ ] `TracyManager` 组件已添加到场景
|
||||
|
||||
### 获取帮助
|
||||
|
||||
如果遇到问题:
|
||||
|
||||
1. 查看 [QUICKSTART.md](QUICKSTART.md) 的故障排除章节
|
||||
2. 查看 [完整集成指南](../UNITY_INTEGRATION_GUIDE.md)
|
||||
3. 查看 [Tracy 官方文档](https://github.com/wolfpld/tracy)
|
||||
4. 检查 Unity Console 的错误消息
|
||||
|
||||
## 📚 相关资源
|
||||
|
||||
### 文档
|
||||
|
||||
- [快速开始指南](QUICKSTART.md) - 5分钟集成
|
||||
- [完整集成指南](../UNITY_INTEGRATION_GUIDE.md) - 详细文档
|
||||
- [Tracy 官方手册](https://github.com/wolfpld/tracy/releases/latest/download/tracy.pdf) - PDF
|
||||
|
||||
### 链接
|
||||
|
||||
- [Tracy GitHub](https://github.com/wolfpld/tracy) - 官方仓库
|
||||
- [Tracy 演示视频](https://www.youtube.com/watch?v=fB5B46lbapc) - YouTube
|
||||
- [Unity Native Plugins](https://docs.unity3d.com/Manual/NativePlugins.html) - 官方文档
|
||||
|
||||
### 示例项目
|
||||
|
||||
本目录中的示例展示了:
|
||||
- 基本的 Zone 使用
|
||||
- 性能数据绘制
|
||||
- 协程追踪
|
||||
- 多线程支持
|
||||
- 最佳实践
|
||||
|
||||
## 🤝 贡献
|
||||
|
||||
欢迎改进和建议!
|
||||
|
||||
如果你有更好的实现方式或发现了问题,请:
|
||||
1. 修改代码
|
||||
2. 测试你的更改
|
||||
3. 分享你的改进
|
||||
|
||||
## 📄 许可证
|
||||
|
||||
- Tracy: BSD 3-Clause License
|
||||
- 本示例代码: MIT License
|
||||
|
||||
## 🎉 开始使用
|
||||
|
||||
现在你已经了解了整体结构,可以开始集成了!
|
||||
|
||||
**下一步**: 打开 [QUICKSTART.md](QUICKSTART.md) 开始 5 分钟快速集成!
|
||||
|
||||
---
|
||||
|
||||
**祝你使用愉快!** 🚀
|
||||
|
||||
如有任何问题,欢迎查阅文档或在社区寻求帮助。
|
||||
|
||||
@@ -1,24 +1,24 @@
|
||||
/*
|
||||
* Tracy Unity Plugin - 简化版实现
|
||||
* Tracy Unity Plugin - Simplified Implementation
|
||||
*
|
||||
* 这是一个简化的 Tracy Unity Plugin 实现
|
||||
* 用于演示如何将 Tracy 集成到 Unity Native Plugin 中
|
||||
* This is a simplified Tracy Unity Plugin implementation
|
||||
* demonstrating how to integrate Tracy into Unity Native Plugin
|
||||
*
|
||||
* 编译说明:
|
||||
* Windows: cl /LD /MD SimplifiedPlugin.cpp /I"path/to/tracy/public" ws2_32.lib dbghelp.lib
|
||||
* macOS: clang++ -shared -fPIC SimplifiedPlugin.cpp -I"path/to/tracy/public" -o libUnityTracyPlugin.dylib
|
||||
* Linux: g++ -shared -fPIC SimplifiedPlugin.cpp -I"path/to/tracy/public" -o libUnityTracyPlugin.so -lpthread -ldl
|
||||
* Build instructions:
|
||||
* Windows: Use CMake (see CMakeLists.txt)
|
||||
* macOS: Use CMake (see CMakeLists.txt)
|
||||
* Linux: Use CMake (see CMakeLists.txt)
|
||||
*/
|
||||
|
||||
// 定义 Tracy 启用标志
|
||||
#define TRACY_ENABLE
|
||||
#define TRACY_ON_DEMAND
|
||||
#pragma warning(disable:4100)
|
||||
|
||||
#include "tracy/Tracy.hpp"
|
||||
#include <string>
|
||||
#include <cstring>
|
||||
#include <map>
|
||||
#include <stack>
|
||||
|
||||
// 平台特定的导出定义
|
||||
// Platform specific export definition
|
||||
#if defined(_WIN32) || defined(_WIN64)
|
||||
#define UNITY_PLUGIN_EXPORT __declspec(dllexport)
|
||||
#elif defined(__APPLE__) || defined(__linux__)
|
||||
@@ -27,261 +27,121 @@
|
||||
#define UNITY_PLUGIN_EXPORT
|
||||
#endif
|
||||
|
||||
// C 导出函数(Unity 需要 C 链接)
|
||||
extern "C" {
|
||||
std::map<std::string, tracy::SourceLocationData> sourceLocationCache;
|
||||
std::map<std::string, std::string> zoneFunctionNameCache;
|
||||
std::map<std::string, std::string> zoneFilePathCache;
|
||||
std::map<std::string, std::stack<tracy::ScopedZone*>> zoneStackCache;
|
||||
|
||||
/**
|
||||
* 初始化 Tracy
|
||||
* Unity C# 调用: [DllImport] private static extern void TracyInit();
|
||||
*/
|
||||
UNITY_PLUGIN_EXPORT void TracyInit()
|
||||
// C export functions (Unity requires C linkage)
|
||||
extern "C"
|
||||
{
|
||||
// Tracy 会自动初始化,这里可以添加额外的初始化逻辑
|
||||
// 例如:设置采样率、配置选项等
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭 Tracy
|
||||
* Unity C# 调用: [DllImport] private static extern void TracyShutdown();
|
||||
*/
|
||||
UNITY_PLUGIN_EXPORT void TracyShutdown()
|
||||
{
|
||||
// Tracy 会在程序退出时自动清理
|
||||
// 这里可以添加自定义的清理逻辑
|
||||
}
|
||||
|
||||
/**
|
||||
* 标记帧边界
|
||||
* Unity C# 调用: [DllImport] private static extern void TracyFrameMark();
|
||||
*/
|
||||
UNITY_PLUGIN_EXPORT void TracyFrameMark()
|
||||
{
|
||||
FrameMark;
|
||||
}
|
||||
|
||||
/**
|
||||
* 绘制数值
|
||||
* Unity C# 调用: [DllImport] private static extern void TracyPlotValue(string name, double value);
|
||||
*/
|
||||
UNITY_PLUGIN_EXPORT void TracyPlotValue(const char* name, double value)
|
||||
{
|
||||
if (name != nullptr)
|
||||
/**
|
||||
* Initialize Tracy
|
||||
* Unity C# call: [DllImport] private static extern void TracyInit();
|
||||
*/
|
||||
UNITY_PLUGIN_EXPORT void TracyInit()
|
||||
{
|
||||
TracyPlot(name, value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送消息
|
||||
* Unity C# 调用: [DllImport] private static extern void TracyMessage(string message);
|
||||
*/
|
||||
UNITY_PLUGIN_EXPORT void TracyMessage(const char* message)
|
||||
{
|
||||
if (message != nullptr)
|
||||
{
|
||||
TracyMessage(message, std::strlen(message));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置线程名称
|
||||
* Unity C# 调用: [DllImport] private static extern void TracySetThreadName(string name);
|
||||
*/
|
||||
UNITY_PLUGIN_EXPORT void TracySetThreadName(const char* name)
|
||||
{
|
||||
if (name != nullptr)
|
||||
{
|
||||
tracy::SetThreadName(name);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 开始一个命名的 Zone
|
||||
* Unity C# 调用: [DllImport] private static extern void TracyZoneBegin(string name);
|
||||
*
|
||||
* 注意: 这是简化版实现,实际使用中需要更复杂的 Zone 管理
|
||||
*/
|
||||
UNITY_PLUGIN_EXPORT void TracyZoneBegin(const char* name)
|
||||
{
|
||||
if (name != nullptr)
|
||||
{
|
||||
// 简化版: 使用动态分配的 Zone
|
||||
// 实际应用中需要管理 Zone 的生命周期
|
||||
|
||||
// 方案1: 使用全局 Zone 栈(简单但不支持多线程)
|
||||
// 方案2: 使用线程局部存储(复杂但支持多线程)
|
||||
// 方案3: 返回 Zone ID 给 C#,让 C# 管理(推荐)
|
||||
|
||||
// 这里使用宏创建一个 Zone
|
||||
// 注意:这只是示例,实际使用需要更好的管理方式
|
||||
ZoneName(name, std::strlen(name));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 结束当前 Zone
|
||||
* Unity C# 调用: [DllImport] private static extern void TracyZoneEnd();
|
||||
*/
|
||||
UNITY_PLUGIN_EXPORT void TracyZoneEnd()
|
||||
{
|
||||
// 简化版: 与 ZoneBegin 配对使用
|
||||
// 实际应用中需要管理 Zone 的结束
|
||||
}
|
||||
|
||||
/**
|
||||
* Unity 插件生命周期函数 - 加载时调用
|
||||
*/
|
||||
UNITY_PLUGIN_EXPORT void UnityPluginLoad()
|
||||
{
|
||||
// 可选:在插件加载时执行初始化
|
||||
}
|
||||
|
||||
/**
|
||||
* Unity 插件生命周期函数 - 卸载时调用
|
||||
*/
|
||||
UNITY_PLUGIN_EXPORT void UnityPluginUnload()
|
||||
{
|
||||
// 可选:在插件卸载时执行清理
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
|
||||
/*
|
||||
* 高级实现示例 - Zone 管理
|
||||
*
|
||||
* 下面是一个更完善的 Zone 管理实现示例
|
||||
* 可以根据需要扩展
|
||||
*/
|
||||
|
||||
#ifdef ADVANCED_ZONE_MANAGEMENT
|
||||
|
||||
#include <unordered_map>
|
||||
#include <stack>
|
||||
#include <mutex>
|
||||
|
||||
// Zone 管理器(线程安全)
|
||||
class ZoneManager
|
||||
{
|
||||
private:
|
||||
struct ThreadZones
|
||||
{
|
||||
std::stack<tracy::ScopedZone*> zones;
|
||||
};
|
||||
|
||||
std::unordered_map<std::thread::id, ThreadZones> threadZones;
|
||||
std::mutex mutex;
|
||||
|
||||
public:
|
||||
void BeginZone(const char* name, const char* function, const char* file, uint32_t line)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex);
|
||||
|
||||
auto threadId = std::this_thread::get_id();
|
||||
auto& zones = threadZones[threadId].zones;
|
||||
|
||||
// 创建源位置信息
|
||||
static const tracy::SourceLocationData loc{name, function, file, line, 0};
|
||||
|
||||
// 创建 Zone(注意:需要在堆上分配)
|
||||
auto* zone = new tracy::ScopedZone(&loc, true);
|
||||
zones.push(zone);
|
||||
// Tracy initializes automatically, additional initialization logic can be added here
|
||||
}
|
||||
|
||||
void EndZone()
|
||||
/**
|
||||
* Shutdown Tracy
|
||||
* Unity C# call: [DllImport] private static extern void TracyShutdown();
|
||||
*/
|
||||
UNITY_PLUGIN_EXPORT void TracyShutdown()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex);
|
||||
|
||||
auto threadId = std::this_thread::get_id();
|
||||
auto it = threadZones.find(threadId);
|
||||
|
||||
if (it != threadZones.end() && !it->second.zones.empty())
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark frame boundary
|
||||
* Unity C# call: [DllImport] private static extern void TracyFrameMark();
|
||||
*/
|
||||
UNITY_PLUGIN_EXPORT void TracyFrameMark()
|
||||
{
|
||||
FrameMark;
|
||||
}
|
||||
|
||||
/**
|
||||
* Plot value
|
||||
* Unity C# call: [DllImport] private static extern void TracyPlotValue(string name, double value);
|
||||
*/
|
||||
UNITY_PLUGIN_EXPORT void TracyPlotValue(const char* name, double value)
|
||||
{
|
||||
if (name != nullptr)
|
||||
{
|
||||
auto* zone = it->second.zones.top();
|
||||
it->second.zones.pop();
|
||||
delete zone;
|
||||
TracyPlot(name, value);
|
||||
}
|
||||
}
|
||||
|
||||
void ClearThread()
|
||||
/**
|
||||
* Send message
|
||||
* Unity C# call: [DllImport] private static extern void TracySendMessage(string message);
|
||||
*/
|
||||
UNITY_PLUGIN_EXPORT void TracySendMessage(const char* message)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex);
|
||||
|
||||
auto threadId = std::this_thread::get_id();
|
||||
auto it = threadZones.find(threadId);
|
||||
|
||||
if (it != threadZones.end())
|
||||
if (message != nullptr)
|
||||
{
|
||||
// 清理所有未结束的 Zone
|
||||
while (!it->second.zones.empty())
|
||||
{
|
||||
delete it->second.zones.top();
|
||||
it->second.zones.pop();
|
||||
}
|
||||
threadZones.erase(it);
|
||||
TracyMessage(message, std::strlen(message));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// 全局 Zone 管理器实例
|
||||
static ZoneManager g_zoneManager;
|
||||
/**
|
||||
* Set thread name
|
||||
* Unity C# call: [DllImport] private static extern void TracySetThreadName(string name);
|
||||
*/
|
||||
UNITY_PLUGIN_EXPORT void TracySetThreadName(const char* name)
|
||||
{
|
||||
if (name != nullptr)
|
||||
{
|
||||
tracy::SetThreadName(name);
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" {
|
||||
/**
|
||||
* Unity plugin lifecycle function - called on load
|
||||
*/
|
||||
UNITY_PLUGIN_EXPORT void UnityPluginLoad()
|
||||
{
|
||||
// Optional: perform initialization when plugin loads
|
||||
}
|
||||
|
||||
UNITY_PLUGIN_EXPORT void TracyZoneBeginAdvanced(const char* name, const char* function, const char* file, int line)
|
||||
{
|
||||
g_zoneManager.BeginZone(name, function, file, static_cast<uint32_t>(line));
|
||||
}
|
||||
/**
|
||||
* Unity plugin lifecycle function - called on unload
|
||||
*/
|
||||
UNITY_PLUGIN_EXPORT void UnityPluginUnload()
|
||||
{
|
||||
// Optional: perform cleanup when plugin unloads
|
||||
TracyShutdown();
|
||||
}
|
||||
|
||||
UNITY_PLUGIN_EXPORT void TracyZoneEndAdvanced()
|
||||
{
|
||||
g_zoneManager.EndZone();
|
||||
}
|
||||
UNITY_PLUGIN_EXPORT void TracyZoneScopedBegin(
|
||||
const char* name,
|
||||
const char* functionName,
|
||||
const char* filePath,
|
||||
int lineNumber
|
||||
)
|
||||
{
|
||||
std::string nameStr(name);
|
||||
auto iter = sourceLocationCache.find(nameStr);
|
||||
if (iter == sourceLocationCache.end())
|
||||
{
|
||||
zoneFunctionNameCache[nameStr] = functionName;
|
||||
zoneFilePathCache[nameStr] = filePath;
|
||||
iter = sourceLocationCache.insert(sourceLocationCache.end(), std::make_pair(nameStr, tracy::SourceLocationData{}));
|
||||
iter->second.name = iter->first.c_str();
|
||||
iter->second.function = zoneFunctionNameCache[nameStr].c_str();
|
||||
iter->second.file = zoneFilePathCache[nameStr].c_str();
|
||||
iter->second.line = static_cast<uint32_t>(lineNumber);
|
||||
iter->second.color = 0;
|
||||
}
|
||||
zoneStackCache[nameStr].push(new tracy::ScopedZone(&iter->second, 0, true));
|
||||
}
|
||||
|
||||
UNITY_PLUGIN_EXPORT void TracyClearThreadZones()
|
||||
{
|
||||
g_zoneManager.ClearThread();
|
||||
}
|
||||
UNITY_PLUGIN_EXPORT void TracyZoneScopedEnd(const char* name)
|
||||
{
|
||||
delete zoneStackCache[name].top();
|
||||
zoneStackCache[name].pop();
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
|
||||
#endif // ADVANCED_ZONE_MANAGEMENT
|
||||
|
||||
/*
|
||||
* 编译和部署说明:
|
||||
*
|
||||
* 1. Windows (Visual Studio):
|
||||
* - 创建 DLL 项目
|
||||
* - 添加 Tracy 源文件: tracy/public/TracyClient.cpp
|
||||
* - 包含目录: tracy/public
|
||||
* - 链接库: ws2_32.lib dbghelp.lib
|
||||
* - 输出: UnityTracyPlugin.dll
|
||||
*
|
||||
* 2. macOS:
|
||||
* clang++ -std=c++17 -shared -fPIC \
|
||||
* SimplifiedPlugin.cpp \
|
||||
* tracy/public/TracyClient.cpp \
|
||||
* -I tracy/public \
|
||||
* -DTRACY_ENABLE -DTRACY_ON_DEMAND \
|
||||
* -o libUnityTracyPlugin.dylib
|
||||
*
|
||||
* 3. Linux:
|
||||
* g++ -std=c++17 -shared -fPIC \
|
||||
* SimplifiedPlugin.cpp \
|
||||
* tracy/public/TracyClient.cpp \
|
||||
* -I tracy/public \
|
||||
* -DTRACY_ENABLE -DTRACY_ON_DEMAND \
|
||||
* -lpthread -ldl \
|
||||
* -o libUnityTracyPlugin.so
|
||||
*
|
||||
* 4. Android (NDK):
|
||||
* 在 Android.mk 或 CMakeLists.txt 中配置
|
||||
*
|
||||
* 5. iOS:
|
||||
* 使用 Xcode 编译为静态库 (.a)
|
||||
*
|
||||
* 部署到 Unity:
|
||||
* - 将编译好的库文件复制到 Unity 项目的 Assets/Plugins/ 目录
|
||||
* - 根据平台放置在相应的子目录中
|
||||
* - 配置 Plugin Import Settings 以匹配目标平台
|
||||
*/
|
||||
|
||||
|
||||
@@ -1,396 +0,0 @@
|
||||
using UnityEngine;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using TracyProfiler;
|
||||
|
||||
namespace TracyProfiler.Examples
|
||||
{
|
||||
/// <summary>
|
||||
/// Tracy 使用示例
|
||||
/// 展示如何在不同场景下使用 Tracy 性能分析
|
||||
/// </summary>
|
||||
public class TracyExamples : MonoBehaviour
|
||||
{
|
||||
[Header("测试参数")]
|
||||
[SerializeField] private int heavyComputationIterations = 10000;
|
||||
[SerializeField] private int objectPoolSize = 100;
|
||||
[SerializeField] private bool runContinuousTest = false;
|
||||
|
||||
private List<GameObject> objectPool = new List<GameObject>();
|
||||
|
||||
private void Start()
|
||||
{
|
||||
Tracy.Message("TracyExamples - 示例场景启动");
|
||||
InitializeObjectPool();
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
// 示例 1: 追踪整个 Update 方法
|
||||
using (Tracy.Zone("TracyExamples.Update"))
|
||||
{
|
||||
// 示例 2: 追踪输入处理
|
||||
HandleInput();
|
||||
|
||||
// 示例 3: 追踪游戏逻辑
|
||||
if (runContinuousTest)
|
||||
{
|
||||
UpdateGameLogic();
|
||||
}
|
||||
|
||||
// 示例 4: 绘制自定义数据
|
||||
PlotCustomData();
|
||||
}
|
||||
}
|
||||
|
||||
#region 示例 1: 基础 Zone 使用
|
||||
|
||||
private void HandleInput()
|
||||
{
|
||||
using (Tracy.Zone("Handle Input"))
|
||||
{
|
||||
if (Input.GetKeyDown(KeyCode.Space))
|
||||
{
|
||||
Tracy.Message("用户按下空格键");
|
||||
PerformHeavyComputation();
|
||||
}
|
||||
|
||||
if (Input.GetKeyDown(KeyCode.R))
|
||||
{
|
||||
Tracy.Message("用户按下 R 键 - 重置对象池");
|
||||
ResetObjectPool();
|
||||
}
|
||||
|
||||
if (Input.GetKeyDown(KeyCode.T))
|
||||
{
|
||||
Tracy.Message("用户按下 T 键 - 运行测试");
|
||||
StartCoroutine(RunPerformanceTest());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 示例 2: 计算密集型操作追踪
|
||||
|
||||
private void UpdateGameLogic()
|
||||
{
|
||||
using (Tracy.Zone("Update Game Logic"))
|
||||
{
|
||||
// 模拟一些游戏逻辑
|
||||
ProcessAI();
|
||||
UpdatePhysics();
|
||||
CheckCollisions();
|
||||
}
|
||||
}
|
||||
|
||||
private void ProcessAI()
|
||||
{
|
||||
using (Tracy.Zone("Process AI"))
|
||||
{
|
||||
// 模拟 AI 计算
|
||||
float sum = 0;
|
||||
for (int i = 0; i < 1000; i++)
|
||||
{
|
||||
sum += Mathf.Sin(i) * Mathf.Cos(i);
|
||||
}
|
||||
|
||||
Tracy.Plot("AI Computation Result", sum);
|
||||
}
|
||||
}
|
||||
|
||||
private void UpdatePhysics()
|
||||
{
|
||||
using (Tracy.Zone("Update Physics"))
|
||||
{
|
||||
// 模拟物理更新
|
||||
foreach (var obj in objectPool)
|
||||
{
|
||||
if (obj.activeInHierarchy)
|
||||
{
|
||||
// 简单的物理模拟
|
||||
obj.transform.position += Vector3.down * Time.deltaTime;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void CheckCollisions()
|
||||
{
|
||||
using (Tracy.Zone("Check Collisions"))
|
||||
{
|
||||
// 模拟碰撞检测
|
||||
int activeObjects = 0;
|
||||
foreach (var obj in objectPool)
|
||||
{
|
||||
if (obj.activeInHierarchy)
|
||||
{
|
||||
activeObjects++;
|
||||
}
|
||||
}
|
||||
|
||||
Tracy.Plot("Active Objects", activeObjects);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 示例 3: 重度计算测试
|
||||
|
||||
[ContextMenu("执行重度计算")]
|
||||
public void PerformHeavyComputation()
|
||||
{
|
||||
using (Tracy.Zone("Heavy Computation"))
|
||||
{
|
||||
Tracy.Message($"开始重度计算 ({heavyComputationIterations} 次迭代)");
|
||||
|
||||
// 矩阵运算
|
||||
using (Tracy.Zone("Matrix Operations"))
|
||||
{
|
||||
Matrix4x4 result = Matrix4x4.identity;
|
||||
for (int i = 0; i < heavyComputationIterations; i++)
|
||||
{
|
||||
Matrix4x4 temp = Matrix4x4.TRS(
|
||||
Random.insideUnitSphere,
|
||||
Random.rotation,
|
||||
Vector3.one
|
||||
);
|
||||
result = result * temp;
|
||||
}
|
||||
}
|
||||
|
||||
// 数学运算
|
||||
using (Tracy.Zone("Math Operations"))
|
||||
{
|
||||
double sum = 0;
|
||||
for (int i = 0; i < heavyComputationIterations; i++)
|
||||
{
|
||||
sum += System.Math.Sqrt(i) * System.Math.Sin(i) * System.Math.Cos(i);
|
||||
}
|
||||
Tracy.Plot("Math Result", sum);
|
||||
}
|
||||
|
||||
Tracy.Message("重度计算完成");
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 示例 4: 对象池管理
|
||||
|
||||
private void InitializeObjectPool()
|
||||
{
|
||||
using (Tracy.Zone("Initialize Object Pool"))
|
||||
{
|
||||
Tracy.Message($"初始化对象池 (大小: {objectPoolSize})");
|
||||
|
||||
for (int i = 0; i < objectPoolSize; i++)
|
||||
{
|
||||
GameObject obj = GameObject.CreatePrimitive(PrimitiveType.Cube);
|
||||
obj.name = $"PoolObject_{i}";
|
||||
obj.transform.position = Random.insideUnitSphere * 10f;
|
||||
obj.SetActive(false);
|
||||
objectPool.Add(obj);
|
||||
}
|
||||
|
||||
Tracy.Plot("Object Pool Size", objectPoolSize);
|
||||
}
|
||||
}
|
||||
|
||||
[ContextMenu("重置对象池")]
|
||||
public void ResetObjectPool()
|
||||
{
|
||||
using (Tracy.Zone("Reset Object Pool"))
|
||||
{
|
||||
foreach (var obj in objectPool)
|
||||
{
|
||||
obj.transform.position = Random.insideUnitSphere * 10f;
|
||||
obj.SetActive(Random.value > 0.5f);
|
||||
}
|
||||
|
||||
Tracy.Message("对象池已重置");
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 示例 5: 协程性能追踪
|
||||
|
||||
[ContextMenu("运行性能测试")]
|
||||
public void StartPerformanceTest()
|
||||
{
|
||||
StartCoroutine(RunPerformanceTest());
|
||||
}
|
||||
|
||||
private IEnumerator RunPerformanceTest()
|
||||
{
|
||||
Tracy.Message("=== 性能测试开始 ===");
|
||||
|
||||
// 测试 1: 快速操作
|
||||
using (Tracy.Zone("Test: Fast Operations"))
|
||||
{
|
||||
for (int i = 0; i < 100; i++)
|
||||
{
|
||||
float temp = Mathf.Sin(i);
|
||||
}
|
||||
}
|
||||
|
||||
yield return null;
|
||||
|
||||
// 测试 2: 中等操作
|
||||
using (Tracy.Zone("Test: Medium Operations"))
|
||||
{
|
||||
for (int i = 0; i < 1000; i++)
|
||||
{
|
||||
Vector3 temp = Random.insideUnitSphere;
|
||||
}
|
||||
}
|
||||
|
||||
yield return new WaitForSeconds(0.1f);
|
||||
|
||||
// 测试 3: 慢速操作
|
||||
using (Tracy.Zone("Test: Slow Operations"))
|
||||
{
|
||||
for (int i = 0; i < objectPoolSize; i++)
|
||||
{
|
||||
objectPool[i].SetActive(true);
|
||||
objectPool[i].transform.position = Random.insideUnitSphere * 20f;
|
||||
}
|
||||
}
|
||||
|
||||
yield return null;
|
||||
|
||||
Tracy.Message("=== 性能测试完成 ===");
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 示例 6: 自定义数据绘制
|
||||
|
||||
private void PlotCustomData()
|
||||
{
|
||||
using (Tracy.Zone("Plot Custom Data"))
|
||||
{
|
||||
// 绘制内存使用
|
||||
long memoryUsed = System.GC.GetTotalMemory(false);
|
||||
Tracy.Plot("Custom Memory (MB)", memoryUsed / (1024.0 * 1024.0));
|
||||
|
||||
// 绘制对象计数
|
||||
int activeCount = 0;
|
||||
foreach (var obj in objectPool)
|
||||
{
|
||||
if (obj.activeInHierarchy) activeCount++;
|
||||
}
|
||||
Tracy.Plot("Active Pool Objects", activeCount);
|
||||
|
||||
// 绘制帧时间
|
||||
Tracy.Plot("Custom Frame Time (ms)", Time.deltaTime * 1000f);
|
||||
|
||||
// 绘制时间戳
|
||||
Tracy.Plot("Time Since Startup", Time.realtimeSinceStartup);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 示例 7: 条件性能追踪
|
||||
|
||||
/// <summary>
|
||||
/// 演示如何使用条件编译来控制 Tracy 的开销
|
||||
/// </summary>
|
||||
private void ConditionalProfiling()
|
||||
{
|
||||
#if TRACY_ENABLE
|
||||
// 只有在定义了 TRACY_ENABLE 时才执行的代码
|
||||
using (Tracy.Zone("Conditional Profiling"))
|
||||
{
|
||||
// 详细的性能追踪
|
||||
DetailedPerformanceTracking();
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
private void DetailedPerformanceTracking()
|
||||
{
|
||||
// 非常细粒度的性能追踪
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
using (Tracy.Zone($"Iteration {i}"))
|
||||
{
|
||||
// 每次迭代的详细追踪
|
||||
System.Threading.Thread.Sleep(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
private void OnDestroy()
|
||||
{
|
||||
// 清理对象池
|
||||
using (Tracy.Zone("Cleanup Object Pool"))
|
||||
{
|
||||
foreach (var obj in objectPool)
|
||||
{
|
||||
if (obj != null)
|
||||
{
|
||||
Destroy(obj);
|
||||
}
|
||||
}
|
||||
objectPool.Clear();
|
||||
|
||||
Tracy.Message("TracyExamples - 场景清理完成");
|
||||
}
|
||||
}
|
||||
|
||||
#if UNITY_EDITOR
|
||||
[ContextMenu("切换连续测试")]
|
||||
private void ToggleContinuousTest()
|
||||
{
|
||||
runContinuousTest = !runContinuousTest;
|
||||
Tracy.Message($"连续测试: {(runContinuousTest ? "启用" : "禁用")}");
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 演示如何在自定义类中使用 Tracy
|
||||
/// </summary>
|
||||
public class CustomSystem
|
||||
{
|
||||
private string systemName;
|
||||
|
||||
public CustomSystem(string name)
|
||||
{
|
||||
systemName = name;
|
||||
Tracy.Message($"{systemName} - 系统创建");
|
||||
}
|
||||
|
||||
public void Update()
|
||||
{
|
||||
using (Tracy.Zone($"{systemName}.Update"))
|
||||
{
|
||||
// 系统更新逻辑
|
||||
ProcessData();
|
||||
UpdateState();
|
||||
}
|
||||
}
|
||||
|
||||
private void ProcessData()
|
||||
{
|
||||
using (Tracy.Zone($"{systemName}.ProcessData"))
|
||||
{
|
||||
// 数据处理
|
||||
}
|
||||
}
|
||||
|
||||
private void UpdateState()
|
||||
{
|
||||
using (Tracy.Zone($"{systemName}.UpdateState"))
|
||||
{
|
||||
// 状态更新
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.CompilerServices;
|
||||
using UnityEngine;
|
||||
|
||||
namespace TracyProfiler
|
||||
@@ -31,16 +32,17 @@ namespace TracyProfiler
|
||||
private static extern void TracyPlotValue(string name, double value);
|
||||
|
||||
[DllImport(DLL_NAME, CallingConvention = CallingConvention.Cdecl)]
|
||||
private static extern void TracyMessage(string message);
|
||||
private static extern void TracySendMessage(string message);
|
||||
|
||||
[DllImport(DLL_NAME, CallingConvention = CallingConvention.Cdecl)]
|
||||
private static extern void TracySetThreadName(string name);
|
||||
|
||||
[DllImport(DLL_NAME, CallingConvention = CallingConvention.Cdecl)]
|
||||
private static extern void TracyZoneBegin(string name);
|
||||
private static extern void TracyZoneScopedBegin(string name, string function = "", string file = "",
|
||||
int line = 0);
|
||||
|
||||
[DllImport(DLL_NAME, CallingConvention = CallingConvention.Cdecl)]
|
||||
private static extern void TracyZoneEnd();
|
||||
private static extern void TracyZoneScopedEnd(string name);
|
||||
|
||||
#endregion
|
||||
|
||||
@@ -70,7 +72,7 @@ namespace TracyProfiler
|
||||
|
||||
try
|
||||
{
|
||||
#if TRACY_ENABLE || UNITY_EDITOR
|
||||
#if TRACY_ENABLE
|
||||
TracyInit();
|
||||
s_initialized = true;
|
||||
Debug.Log("[Tracy] 性能分析器已初始化");
|
||||
@@ -154,7 +156,7 @@ namespace TracyProfiler
|
||||
public static void Message(string message)
|
||||
{
|
||||
if (!s_initialized || !s_enabled) return;
|
||||
TracyMessage(message);
|
||||
TracySendMessage(message);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -176,15 +178,14 @@ namespace TracyProfiler
|
||||
private bool isValid;
|
||||
private string zoneName;
|
||||
|
||||
public ZoneScope(string name)
|
||||
public ZoneScope(string name, string function = "", string file = "", int line = 0)
|
||||
{
|
||||
zoneName = name;
|
||||
isValid = s_initialized && s_enabled;
|
||||
|
||||
#if TRACY_ENABLE
|
||||
if (isValid)
|
||||
{
|
||||
TracyZoneBegin(name);
|
||||
TracyZoneScopedBegin(name, function, file, line);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -194,7 +195,7 @@ namespace TracyProfiler
|
||||
#if TRACY_ENABLE
|
||||
if (isValid && s_initialized && s_enabled)
|
||||
{
|
||||
TracyZoneEnd();
|
||||
TracyZoneScopedEnd(zoneName);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -210,31 +211,12 @@ namespace TracyProfiler
|
||||
/// // 要追踪的代码
|
||||
/// }
|
||||
/// </example>
|
||||
public static ZoneScope Zone(string name)
|
||||
public static ZoneScope Zone(string name,
|
||||
[CallerMemberName] string function = "",
|
||||
[CallerFilePath] string file = "",
|
||||
[CallerLineNumber] int line = 0)
|
||||
{
|
||||
return new ZoneScope(name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 开始一个命名的 Zone
|
||||
/// 注意:必须手动调用 EndZone() 结束,推荐使用 Zone() 方法配合 using 语句
|
||||
/// </summary>
|
||||
[System.Diagnostics.Conditional("TRACY_ENABLE")]
|
||||
public static void BeginZone(string name)
|
||||
{
|
||||
if (!s_initialized || !s_enabled) return;
|
||||
TracyZoneBegin(name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 结束当前 Zone
|
||||
/// 注意:必须与 BeginZone() 配对使用
|
||||
/// </summary>
|
||||
[System.Diagnostics.Conditional("TRACY_ENABLE")]
|
||||
public static void EndZone()
|
||||
{
|
||||
if (!s_initialized || !s_enabled) return;
|
||||
TracyZoneEnd();
|
||||
return new ZoneScope(name, function, file, line);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user