How to properly save time in exact milliseconds

I am attempting to start a timer when the player clicks a button and stop the timer when the player touches a part. These function are ran through remote events and work fine, however, the gui displaying the time is 15-19 milliseconds quicker than the time being saved and sent to the server. For example, if the gui is displaying 00:06.633, the game will save the time as 00:06.650

local startTime = 0.000
local updateTimeLabelConn = nil

updateTimeLabelConn = game:GetService("RunService").Heartbeat:Connect(function()
	local currentTime = (os.clock() - startTime) * 1000
	local minutes = math.floor(currentTime / 60000) -- Convert to minutes
	local seconds = math.floor((currentTime % 60000) / 1000) -- Convert to seconds
	local milliseconds = math.floor(currentTime % 1000)
	timeLabel.Text = string.format("⏱️ %02d:%02d.%03d", minutes, seconds, milliseconds)
end)
FinishedEvent.OnClientEvent:Connect(function(level)
	if updateTimeLabelConn then
		updateTimeLabelConn:Disconnect()
	end

	local finalTime = (os.clock() - startTime) * 1000

	local minutes = math.floor(finalTime / 60000)
	local seconds = math.floor((finalTime % 60000) / 1000)
	local milliseconds = math.floor(finalTime % 1000)
	local formattedTime = string.format("%02d:%02d.%03d", minutes, seconds, milliseconds)

	print("Final Time:", formattedTime)
	CompareTimeEvent:FireServer(finalTime, level)
end)

I believe the issue has something to do with the connection being stopped before the time is saved but I have tried changing how I save the time and when I save the time and it doesn’t really fix the actual issue. Could it also be the fact that I am attempting to save to the thousandths instead of hundredths?

Also I couldn’t find any solutions to this on the DevForum or YouTube.

Try using this solution. Get script execution time - Help and Feedback / Scripting Support - Developer Forum | Roblox This will return the amount of time something is executed with ms

1 Like