|
本文主要介绍IOS下使用内存和剩余内存的获取,由于有内存分页偏移,所以会有一定误差,但是不影响我们做判断。实现主要有两步,第一步:ios端从底层代码获取内存值;第二步:c#端获取并展示
第一步:ios端从底层代码获取内存值
在你的 UnityAppController+Rendering.mm (注意:这个随意,只要能获取到就行,我是添加到这个类里面的)文件中添加如下代码,作为ios端获取的值
#include <mach/mach_time.h>
#include <mach/mach.h>
#include <mach/mach_host.h>
#include <mach/task_info.h>
#include <mach/task.h>
//获取使用了的内存
static float GetTotalPhysicsMemory()
{
int64_t memoryUsageInByte = 0;
task_vm_info_data_t vmInfo;
mach_msg_type_number_t count = TASK_VM_INFO_COUNT;
kern_return_t kernelReturn = task_info(mach_task_self(),
TASK_VM_INFO,
(task_info_t) &vmInfo,
&count);
if(kernelReturn == KERN_SUCCESS) {
memoryUsageInByte = vmInfo.phys_footprint;
}
else {
NSLog(@&#34;Error with task_info(): %s&#34;, mach_error_string(kernelReturn));
}
return memoryUsageInByte/1024.0/1024.0;
}
extern &#34;C&#34; float _Get_Profiler_TotalPhysicMemory(){return GetTotalPhysicsMemory();}
//获取剩余内存
static float IosGetAvailableMemory()
{
int64_t memoryInByte = 0;
vm_statistics_data_t vmStats;
mach_msg_type_number_t infoCount = HOST_VM_INFO_COUNT;
kern_return_t kernReturn = host_statistics(mach_host_self(),
HOST_VM_INFO,
(host_info_t)&vmStats,
&infoCount);
if (kernReturn == KERN_SUCCESS) {
memoryInByte = ((vm_page_size * vmStats.free_count
+ vm_page_size * vmStats.inactive_count));
}else{
printf(&#34;---->Error Fetch&#34;);
}
return memoryInByte/1024.0/1024.0;
}
extern &#34;C&#34; float _Get_Profiler_IosGetAvailableMemory(){return IosGetAvailableMemory();}第二步:c#端获取并展示
string showMem;
private void Update()
{
#if (UNITY_IPHONE && !UNITY_EDITOR)
showMem = string.Format(&#34;(使用内存:{0} - 剩余内存:{1})&#34;
, Get_Profiler_TotalPhysicMemory()
, Get_Profiler_IosGetAvailableMemory());
Debug.LogErrorFormat(showMem);
#endif
}
#if (UNITY_IPHONE && !UNITY_EDITOR)
[DllImport(&#34;__Internal&#34;)]
static extern float _Get_Profiler_TotalPhysicMemory( );
public static float Get_Profiler_TotalPhysicMemory( )
{
return _Get_Profiler_TotalPhysicMemory( );
}
#endif
#if (UNITY_IPHONE && !UNITY_EDITOR)
[DllImport(&#34;__Internal&#34;)]
static extern float _Get_Profiler_IosGetAvailableMemory( );
public static float Get_Profiler_IosGetAvailableMemory( )
{
return _Get_Profiler_IosGetAvailableMemory( );
}
#endif
private void OnGUI()
{
GUILayout.Label(showMem);
}
IPad 运行效果
XCode真实运行截图
其他:你可以将ios端的代码集成到你的打包CI上,这样每次生成的XCode代码就自动集成了对应的功能。 然后可以通过宏命令在Debug包展示对应的功能即可 |
本帖子中包含更多资源
您需要 登录 才可以下载或查看,没有账号?立即注册
×
|