EmbarkStudios / physx-rs

🎳 Rust binding for NVIDIA PhysX 🦀
http://embark.rs
Apache License 2.0
652 stars 42 forks source link

Add a simple memory profiler #93

Open emilk opened 3 years ago

emilk commented 3 years ago

I want to know how much memory PhysX is using.

It seems like physx-rs could overload PxAllocatorCallback to add simple tracking of used memory. This could then be queried like scene.bytes_allocated(). I would assume such an overload would have so little overhead that it wouldn't need to be feature-gated, but if it does have overhead then maybe a simple SceneBuilder flag to turn it on could be considered.

PxAllocatorCallback also supplies a typeName for the allocated resource, so in the future one could consider returning a more detailed HashMap<String, usize> describing what is using memory, though I am not sure if such detail would be useful in practice.

hrydgard commented 3 years ago

I'm going to add a simple interface that lets you pass in callbacks that will be called on alloc/dealloc. That lets users of the library implement their own tracking, with zero overhead if you don't use it.

repi commented 3 years ago

Assume PhysX does support overriding their allocator also? Could be quite nice to support overriding it and connect it to the Rust global memory allocator (or rather: A Rust memory allocator of the users choosing) through the standard trait or a custom one. This is what we use in our engine and great to have most heap allocations in the same main allocator. Assuming the interfaces and needs are similar.

hrydgard commented 3 years ago

Yeah, we can also replace the whole allocator. Can try that instead. Physx does send in a bit of extra metadata that we really want to track separately (as Emil mentions), but can then pass through to a Rust alloc.

repi commented 3 years ago

Cool, worth a shot

Hentropy commented 3 years ago

I implemented a super rudimentary tracking allocator here. If the allocation name feature works, that would enable a proper type aware allocator which would be amazing, but IIRC it's debug only, and debug doesn't work or something. I'd love to be wrong there though. Without that, the allocator is a C-style void-pointer allocator, and wrapping Rust's lovely type aware one in that feels dirty.

hrydgard commented 3 years ago

The allocation name feature actually kinda mostly works in release mode, you just have to call
foundation.set_report_allocation_names(true);. PhysX does a quite good job of pooling internally so most of what you'll see are pools of various types.

In our application we implemented a tracker on top of the trampoline I added in https://github.com/EmbarkStudios/physx-rs/pull/94 , actually very similar to yours.