Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <memory>
- #include <vector>
- #include <algorithm>
- #include "/opt/cpp/include/utils/sole_ptr.hpp"
- struct GameObject {
- virtual void foo() {
- // dummy function
- }
- };
- // shared-weak-Ansatz
- using SharedGO = std::shared_ptr<GameObject>;
- using WeakGO = std::weak_ptr<GameObject>;
- // sole-dynamic-Ansatz
- using SoleGO = sole_ptr<GameObject>;
- using DynamicGO = dynamic_ptr<GameObject>;
- // unique-raw-Ansatz
- using UniqueGO = std::unique_ptr<GameObject>;
- using RawGO = GameObject*;
- // ---------------------------------------------------------------------------
- int const NUM_OBJECTS = 100;
- int const NUM_ITERATIONS = 100000;
- void test_shared() {
- std::vector<SharedGO> dungeon;
- std::vector<WeakGO> ai;
- for (int i = 0; i < NUM_OBJECTS; i++) {
- // GameObject created outside (e.g. via factory)
- SharedGO object{new GameObject()};
- // owning ptr spawned to dungeon; non-owning ptr returned
- dungeon.push_back(std::move(object));
- WeakGO weak{dungeon.back()};
- // non-owning ptr stored in AI's list
- ai.push_back(weak);
- }
- for (int i = 0; i < NUM_ITERATIONS; i++) {
- for (auto&& weak: ai) {
- // dereference ai-focused object
- GameObject& object = *(weak.lock());
- object.foo();
- }
- }
- }
- void test_sole() {
- std::vector<SoleGO> dungeon;
- std::vector<DynamicGO> ai;
- for (int i = 0; i < NUM_OBJECTS; i++) {
- SoleGO object{new GameObject()};
- dungeon.push_back(std::move(object));
- DynamicGO dynamic{dungeon.back()};
- ai.push_back(dynamic);
- }
- for (int i = 0; i < NUM_ITERATIONS; i++) {
- for (auto&& dynamic: ai) {
- GameObject& object = *dynamic;
- object.foo();
- }
- }
- }
- void test_unique() {
- std::vector<UniqueGO> dungeon;
- std::vector<RawGO> ai;
- for (int i = 0; i < NUM_OBJECTS; i++) {
- UniqueGO object{new GameObject()};
- dungeon.push_back(std::move(object));
- RawGO raw {dungeon.back().get()};
- ai.push_back(raw);
- }
- for (int i = 0; i < NUM_ITERATIONS; i++) {
- for (auto&& raw: ai) {
- GameObject& object = *raw;
- object.foo();
- }
- }
- }
- // ---------------------------------------------------------------------------
- #include <chrono>
- #include <functional>
- #include <iostream>
- int messure(std::function<void()> f) {
- std::chrono::time_point<std::chrono::system_clock> start, end;
- start = std::chrono::system_clock::now();
- f();
- end = std::chrono::system_clock::now();
- return std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count();
- }
- int main() {
- std::cout << "shared_ptr & weak_ptr: " << messure([](){ return test_shared(); }) << "ms\n";
- std::cout << "sole_ptr & dynamic_ptr: " << messure([](){ return test_sole(); }) << "ms\n";
- std::cout << "unique_ptr & raw pointer: " << messure([](){ return test_unique(); }) << "ms\n";
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement