function round(num, numDecimalPlaces)
  local mult = 10^(numDecimalPlaces or 0)
  return math.floor(num * mult + 0.5) / mult
end

function get_baseline()
	i = 100
	client.reboot_core()
	t = os.clock()

	while i > 0 do
		emu.frameadvance()
		i = i - 1
	end
	baseline = os.clock() - t
	print('底线:          ' .. round(baseline, 3) .. " 秒")
	return baseline
end

function test_mmf()
	i = 100
	client.reboot_core()
	t = os.clock()
	while i > 0 do
		emu.frameadvance()
		comm.mmfScreenshot()
		i = i - 1
	end
	print('内存分配文件:  ' .. round((os.clock() - t - baseline), 3) .. " 秒")
end

function test_http()
	print("测试 HTTP 服务器")
	client.reboot_core()
	i = 100
	t = os.clock()
	
	while i > 0 do
		emu.frameadvance()
		comm.httpTestGet()
		i = i - 1
	end
	print('HTTP get:     ' ..  round((os.clock() - t - baseline), 3) .. " 秒")
	
	client.reboot_core()
	i = 100
	t = os.clock()
	
	while i > 0 do
		emu.frameadvance()
		comm.httpPostScreenshot()
		i = i - 1
	end
	print('HTTP post:    ' ..  round((os.clock() - t - baseline), 3) .. " 秒")

end

function test_socket()

	i = 100
	client.reboot_core()
	t = os.clock()
	while i > 0 do
		emu.frameadvance()
		comm.socketServerScreenShot()
		i = i - 1
	end
	print('Socket 服务器: ' ..  round((os.clock() - t - baseline), 3) .. " 秒")
end

function test_socketresponse()
	best_time = -100
	timeouts = {1, 2, 3, 4, 5, 10, 20, 25, 50, 100, 250, 500, 1000}
	comm.socketServerSetTimeout(1000)
	resp = comm.socketServerScreenShotResponse()
	for t, timeout in ipairs(timeouts) do
		comm.socketServerSetTimeout(timeout)
		client.reboot_core()
		print("尝试获取 Socket 最短超时")
		i = 100
		t = os.clock()
		while i > 0 do
			emu.frameadvance()
			resp = comm.socketServerScreenShotResponse()
			if resp ~= 'ack' then
				i = -100
				print(resp)
				print("获取响应失败")
			end
			i = i - 1
		end
		if i > -100 then
			print("最短超时: " .. timeout .. " 毫秒")
			print("最快时间: " .. round((os.clock() - t - baseline), 3) .. " 秒")
			break
		end
	end
	
end

function test_http_response()
	err = false
	print("测试 HTTP 服务器响应")
	client.reboot_core()
	i = 100
	
	while i > 0 do
		emu.frameadvance()
		resp = comm.httpTestGet()
		if resp ~= "<html><body><h1>hi!</h1></body></html>" then
			print("获取 HTTP get 响应失败")
			print(resp)
			i = 0
			err = true
		end
		i = i - 1
	end
	if not err then
		print("HTTP GET 看上去挺好: 没有发现错误")
	end
	
	client.reboot_core()
	i = 100
	err = false
	while i > 0 do
		emu.frameadvance()
		resp = comm.httpPostScreenshot()
		if resp ~= "<html><body>OK</body></html>" then
			print("获取 HTTP post 响应失败")
			print(resp)
			i = 0
			err = true
		end
		i = i - 1
	end
	if not err then
		print("HTTP POST 看上去挺好: 没有发现错误")
	end
end

baseline = get_baseline()
test_socket()
test_mmf()
test_http()
print("#####################")
test_http_response()
test_socketresponse()
print()

