all repos — mgba @ 48006dd83ebc8222f9a3e895f79ac278577ce5d2

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