Gas performs two functions. First, it guarantees a prepaid reward for the miners who execute the code and protect the network, even if the execution fails. Second, it ensures that code execution cannot go on longer than the time prepaid for it, reducing the risk of attacks. The cost of gas ensures that the computation time on the network is appropriately priced because EVM commissions are based on the amount of work performed, not the transaction size.