Created
August 25, 2015 14:38
-
-
Save zengjie/546f533c10f3787ea58a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <list> | |
#include <vector> | |
#include <chrono> | |
#include <functional> | |
#include <iostream> | |
struct Position { | |
float x; | |
float y; | |
void update() { | |
// x = 32.f; | |
// y = 64.f; | |
} | |
}; | |
struct Motion { | |
float velocity; | |
float angle; | |
void update() { | |
// velocity = 32.f; | |
// angle = 32.f; | |
} | |
}; | |
struct AIControl { | |
int defence; | |
int state; | |
void update() { | |
defence = 3; | |
// state = 1; | |
} | |
}; | |
class GameEntity { | |
public: | |
GameEntity() { | |
position = new Position(); | |
motion = new Motion(); | |
aiControl = new AIControl(); | |
} | |
virtual ~GameEntity() { | |
if (position) | |
delete position; | |
if (motion) | |
delete motion; | |
if (aiControl) | |
delete aiControl; | |
} | |
void update() { | |
position->update(); | |
motion->update(); | |
aiControl->update(); | |
} | |
private: | |
Position* position; | |
Motion* motion; | |
AIControl* aiControl; | |
}; | |
typedef std::chrono::high_resolution_clock Clock; | |
unsigned long long timeit(std::function<void()> func) { | |
auto t1 = Clock::now(); | |
for (int i = 0; i < 64; i++) { | |
func(); | |
} | |
auto t2 = Clock::now(); | |
auto diff = std::chrono::duration_cast<std::chrono::nanoseconds>(t2 - t1); | |
return diff.count() / 64; | |
} | |
void benchmark(int entityCount) { | |
std::list<GameEntity*> entities; | |
for (int i = 0; i < entityCount; ++i) { | |
auto entity = new GameEntity(); | |
entities.push_back(entity); | |
} | |
auto t1 = timeit([&entities]() { | |
for (auto entity : entities) { | |
entity->update(); | |
} | |
}); | |
for (auto entity : entities) { | |
delete entity; | |
} | |
std::vector<Position> positions; | |
std::vector<Motion> motions; | |
std::vector<AIControl> aiControls; | |
for (int i = 0; i < entityCount; ++i) { | |
Position pos; | |
positions.push_back(std::move(pos)); | |
Motion motion; | |
motions.push_back(std::move(motion)); | |
AIControl aiControl; | |
aiControls.push_back(std::move(aiControl)); | |
} | |
auto t2 = timeit([&]() { | |
for (auto& pos : positions) { | |
pos.update(); | |
} | |
for (auto& motion : motions) { | |
motion.update(); | |
} | |
for (auto& aiControl : aiControls) { | |
aiControl.update(); | |
} | |
}); | |
std::cout << entityCount << "," << t1 * 1.0 / t2 << std::endl; | |
} | |
int main(int argc, char const* argv[]) { | |
int num = 2; | |
for (int i = 1; i < 20; i++) { | |
benchmark(num); | |
num *= 2; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment