How to automatically exit/stop the running instance

Correct, instances are charged for the time they are running. (to the minute, minimum 10 minutes). Instances run from the time they are started via the API until they are stopped via the API. It doesn't matter if any user is logged in via SSH or not. For most automated use cases users never log in - programs are installed and started via start up scripts.

You can view your running instances via the Cloud Console, to confirm if any are currently running.

If you want to stop your instance from inside the instance, the easiest way is to start the instance with the compute-rw Service Account Scope and use gcutil.

For example, to start your instance from the command line with the compute-rw scope:

$ gcutil --project=<project-id> addinstance <instance name> --service_account_scopes=compute-rw

(this is the default when manually creating an instance via the Cloud Console)

Later, after your batch job completes, you can remove the instance from inside the instance:

$ gcutil deleteinstance -f <instance name>

You can put halt command at the end of your batch script (assuming that you output your results on persistent disk). After halt the instance will have a state of TERMINATED and you will not be charged. See https://developers.google.com/compute/docs/pricing scroll downn to "instance uptime"