all repos — mgba @ 9de8f084ba55460b02d300c1dd8b8e6c56f691d5

mGBA Game Boy Advance Emulator

src/platform/test/perf-main.c (view raw)

  1/* Copyright (c) 2013-2015 Jeffrey Pfau
  2 *
  3 * This Source Code Form is subject to the terms of the Mozilla Public
  4 * License, v. 2.0. If a copy of the MPL was not distributed with this
  5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  6#include <mgba/core/blip_buf.h>
  7#include <mgba/core/cheats.h>
  8#include <mgba/core/config.h>
  9#include <mgba/core/core.h>
 10#include <mgba/core/serialize.h>
 11#include <mgba/gb/core.h>
 12#include <mgba/gba/core.h>
 13
 14#include <mgba/feature/commandline.h>
 15#include <mgba-util/socket.h>
 16#include <mgba-util/string.h>
 17#include <mgba-util/vfs.h>
 18
 19#ifdef _3DS
 20#include <3ds.h>
 21#endif
 22#ifdef __SWITCH__
 23#include <switch.h>
 24#endif
 25
 26#include <errno.h>
 27#include <fcntl.h>
 28#include <signal.h>
 29#include <inttypes.h>
 30#include <sys/time.h>
 31
 32#define PERF_OPTIONS "DF:L:NPS:"
 33#define PERF_USAGE \
 34	"\nBenchmark options:\n" \
 35	"  -F FRAMES        Run for the specified number of FRAMES before exiting\n" \
 36	"  -N               Disable video rendering entirely\n" \
 37	"  -P               CSV output, useful for parsing\n" \
 38	"  -S SEC           Run for SEC in-game seconds before exiting\n" \
 39	"  -L FILE          Load a savestate when starting the test\n" \
 40	"  -D               Act as a server"
 41
 42struct PerfOpts {
 43	bool noVideo;
 44	bool csv;
 45	unsigned duration;
 46	unsigned frames;
 47	char* savestate;
 48	bool server;
 49};
 50
 51#ifdef _3DS
 52extern bool allocateRomBuffer(void);
 53FS_Archive sdmcArchive;
 54#endif
 55#ifdef __SWITCH__
 56TimeType __nx_time_type = TimeType_LocalSystemClock;
 57#endif
 58
 59static void _mPerfRunloop(struct mCore* context, int* frames, bool quiet);
 60static void _mPerfShutdown(int signal);
 61static bool _parsePerfOpts(struct mSubParser* parser, int option, const char* arg);
 62static void _log(struct mLogger*, int, enum mLogLevel, const char*, va_list);
 63static bool _mPerfRunCore(const char* fname, const struct mArguments*, const struct PerfOpts*);
 64static bool _mPerfRunServer(const char* listen, const struct mArguments*, const struct PerfOpts*);
 65
 66static bool _dispatchExiting = false;
 67static struct VFile* _savestate = 0;
 68static void* _outputBuffer = NULL;
 69static Socket _socket = INVALID_SOCKET;
 70
 71int main(int argc, char** argv) {
 72#ifdef _3DS
 73	UNUSED(_mPerfShutdown);
 74    gfxInitDefault();
 75    osSetSpeedupEnable(true);
 76	consoleInit(GFX_BOTTOM, NULL);
 77	if (!allocateRomBuffer()) {
 78		return 1;
 79	}
 80#elif defined(__SWITCH__)
 81	UNUSED(_mPerfShutdown);
 82	gfxInitDefault();
 83	consoleInit(NULL);
 84#else
 85	signal(SIGINT, _mPerfShutdown);
 86#endif
 87	int didFail = 0;
 88
 89	struct mLogger logger = { .log = _log };
 90	mLogSetDefaultLogger(&logger);
 91
 92	struct PerfOpts perfOpts = { false, false, 0, 0, 0, false };
 93	struct mSubParser subparser = {
 94		.usage = PERF_USAGE,
 95		.parse = _parsePerfOpts,
 96		.extraOptions = PERF_OPTIONS,
 97		.opts = &perfOpts
 98	};
 99
100	struct mArguments args = {};
101	bool parsed = parseArguments(&args, argc, argv, &subparser);
102	if (!args.fname) {
103		parsed = false;
104	}
105	if (!parsed || args.showHelp) {
106		usage(argv[0], PERF_USAGE);
107		didFail = !parsed;
108		goto cleanup;
109	}
110
111	if (args.showVersion) {
112		version(argv[0]);
113		goto cleanup;
114	}
115
116	if (perfOpts.savestate) {
117		_savestate = VFileOpen(perfOpts.savestate, O_RDONLY);
118		free(perfOpts.savestate);
119	}
120
121	_outputBuffer = malloc(256 * 256 * 4);
122	if (perfOpts.csv) {
123		puts("game_code,frames,duration,renderer");
124	}
125	if (perfOpts.server) {
126		didFail = !_mPerfRunServer(args.fname, &args, &perfOpts);
127	} else {
128		didFail = !_mPerfRunCore(args.fname, &args, &perfOpts);
129	}
130	free(_outputBuffer);
131
132	if (_savestate) {
133		_savestate->close(_savestate);
134	}
135	cleanup:
136	freeArguments(&args);
137
138#ifdef _3DS
139	gfxExit();
140	acExit();
141#elif defined(__SWITCH__)
142	gfxExit();
143#endif
144
145	return didFail;
146}
147
148bool _mPerfRunCore(const char* fname, const struct mArguments* args, const struct PerfOpts* perfOpts) {
149	struct mCore* core = mCoreFind(fname);
150	if (!core) {
151		return false;
152	}
153
154	// TODO: Put back debugger
155	char gameCode[9] = { 0 };
156
157	core->init(core);
158	if (!perfOpts->noVideo) {
159		core->setVideoBuffer(core, _outputBuffer, 256);
160	}
161	mCoreLoadFile(core, fname);
162	mCoreConfigInit(&core->config, "perf");
163	mCoreConfigLoad(&core->config);
164
165	struct mCoreOptions opts = {};
166	mCoreConfigMap(&core->config, &opts);
167	opts.audioSync = false;
168	opts.videoSync = false;
169	applyArguments(args, NULL, &core->config);
170	mCoreConfigLoadDefaults(&core->config, &opts);
171	mCoreConfigSetDefaultValue(&core->config, "idleOptimization", "detect");
172	mCoreLoadConfig(core);
173
174	core->reset(core);
175	if (_savestate) {
176		mCoreLoadStateNamed(core, _savestate, 0);
177	}
178
179	core->getGameCode(core, gameCode);
180
181	int frames = perfOpts->frames;
182	if (!frames) {
183		frames = perfOpts->duration * 60;
184	}
185	struct timeval tv;
186	gettimeofday(&tv, 0);
187	uint64_t start = 1000000LL * tv.tv_sec + tv.tv_usec;
188	_mPerfRunloop(core, &frames, perfOpts->csv);
189	gettimeofday(&tv, 0);
190	uint64_t end = 1000000LL * tv.tv_sec + tv.tv_usec;
191	uint64_t duration = end - start;
192
193	mCoreConfigFreeOpts(&opts);
194	mCoreConfigDeinit(&core->config);
195	core->deinit(core);
196
197	float scaledFrames = frames * 1000000.f;
198	if (perfOpts->csv) {
199		char buffer[256];
200		const char* rendererName;
201		if (perfOpts->noVideo) {
202			rendererName = "none";
203		} else {
204			rendererName = "software";
205		}
206		snprintf(buffer, sizeof(buffer), "%s,%i,%" PRIu64 ",%s\n", gameCode, frames, duration, rendererName);
207		printf("%s", buffer);
208		if (_socket != INVALID_SOCKET) {
209			SocketSend(_socket, buffer, strlen(buffer));
210		}
211	} else {
212		printf("%u frames in %" PRIu64 " microseconds: %g fps (%gx)\n", frames, duration, scaledFrames / duration, scaledFrames / (duration * 60.f));
213	}
214
215	return true;
216}
217
218static void _mPerfRunloop(struct mCore* core, int* frames, bool quiet) {
219	struct timeval lastEcho;
220	gettimeofday(&lastEcho, 0);
221	int duration = *frames;
222	*frames = 0;
223	int lastFrames = 0;
224	while (!_dispatchExiting) {
225		core->runFrame(core);
226		++*frames;
227		++lastFrames;
228		if (!quiet) {
229			struct timeval currentTime;
230			long timeDiff;
231			gettimeofday(&currentTime, 0);
232			timeDiff = currentTime.tv_sec - lastEcho.tv_sec;
233			timeDiff *= 1000;
234			timeDiff += (currentTime.tv_usec - lastEcho.tv_usec) / 1000;
235			if (timeDiff >= 1000) {
236				printf("\033[2K\rCurrent FPS: %g (%gx)", lastFrames / (timeDiff / 1000.0f), lastFrames / (float) (60 * (timeDiff / 1000.0f)));
237				fflush(stdout);
238				lastEcho = currentTime;
239				lastFrames = 0;
240			}
241		}
242		if (duration > 0 && *frames == duration) {
243			break;
244		}
245	}
246	if (!quiet) {
247		printf("\033[2K\r");
248	}
249}
250
251static bool _mPerfRunServer(const char* listen, const struct mArguments* args, const struct PerfOpts* perfOpts) {
252	SocketSubsystemInit();
253	Socket server = SocketOpenTCP(7216, NULL);
254	if (SOCKET_FAILED(server)) {
255		SocketSubsystemDeinit();
256		return false;
257	}
258	if (SOCKET_FAILED(SocketListen(server, 0))) {
259		SocketClose(server);
260		SocketSubsystemDeinit();
261		return false;
262	}
263	_socket = SocketAccept(server, NULL);
264	if (perfOpts->csv) {
265		const char* header = "game_code,frames,duration,renderer\n";
266		SocketSend(_socket, header, strlen(header));
267	}
268	char path[PATH_MAX];
269	memset(path, 0, sizeof(path));
270	ssize_t i;
271	while ((i = SocketRecv(_socket, path, sizeof(path) - 1)) > 0) {
272		path[i] = '\0';
273		char* nl = strchr(path, '\n');
274		if (nl == path) {
275			break;
276		}
277		if (nl) {
278			nl[0] = '\0';
279		}
280		if (!_mPerfRunCore(path, args, perfOpts)) {
281			break;
282		}
283		memset(path, 0, sizeof(path));
284	}
285	SocketClose(_socket);
286	SocketClose(server);
287	SocketSubsystemDeinit();
288	return true;
289}
290
291static void _mPerfShutdown(int signal) {
292	UNUSED(signal);
293	_dispatchExiting = true;
294	SocketClose(_socket);
295}
296
297static bool _parsePerfOpts(struct mSubParser* parser, int option, const char* arg) {
298	struct PerfOpts* opts = parser->opts;
299	errno = 0;
300	switch (option) {
301	case 'D':
302		opts->server = true;
303		return true;
304	case 'F':
305		opts->frames = strtoul(arg, 0, 10);
306		return !errno;
307	case 'N':
308		opts->noVideo = true;
309		return true;
310	case 'P':
311		opts->csv = true;
312		return true;
313	case 'S':
314		opts->duration = strtoul(arg, 0, 10);
315		return !errno;
316	case 'L':
317		opts->savestate = strdup(arg);
318		return true;
319	default:
320		return false;
321	}
322}
323
324static void _log(struct mLogger* log, int category, enum mLogLevel level, const char* format, va_list args) {
325	UNUSED(log);
326	UNUSED(category);
327	UNUSED(level);
328	UNUSED(format);
329	UNUSED(args);
330}