Reduzir a latência usando políticas de posicionamento compacto
Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Neste documento, explicamos como reduzir a latência de rede entre as VMs de um job especificando uma política de posicionamento compacto.
Ter hosts de VM fisicamente mais próximos uns dos outros em uma zona pode reduzir a latência de rede entre as VMs. Esse benefício de desempenho pode ser especialmente útil
para jobs com tarefas fortemente acopladas, como
tarefas que se comunicam usando bibliotecas MPI.
Ao criar um job, você pode exigir que as VMs dele estejam localizadas
mais próximas umas das outras especificando uma política de posicionamento compacto.
Caso contrário, o posicionamento padrão de VMs geralmente distribui as VMs em hosts separados para minimizar o impacto de falhas de energia.
Para saber mais sobre políticas de posicionamento compacto, consulte
Sobre políticas de posicionamento
na documentação do Compute Engine.
Quando você especifica que um job use uma política de posicionamento compacto,
o Batch cria e exclui automaticamente uma
política de posicionamento compacto para as VMs do job. Não é possível especificar uma política de posicionamento compacto
existente para um job.
Não é possível especificar um número de VMs para a política de posicionamento compacto.
A política de posicionamento compacto para um job é aplicada independente de quantas
VMs o job executa.
Criar e executar um job que usa uma política de posicionamento
É possível especificar que um job use uma política de posicionamento compacto definindo o campo collocation como COLLOCATED usando a CLI gcloud ou a API Batch.
gcloud
Crie um arquivo JSON que especifique os detalhes de configuração do job e defina o campo collocation como COLLOCATED.
Por exemplo, para criar um job de script básico que especifica uma
política de posicionamento compacto, crie um arquivo JSON com o seguinte conteúdo:
{"taskGroups":[{"taskSpec":{"runnables":[{"script":{"text":"echo Hello world from task ${BATCH_TASK_INDEX}"}}]},"taskCount":3}],"allocationPolicy":{"placement":{"collocation":"COLLOCATED"}},"logsPolicy":{"destination":"CLOUD_LOGGING"}}
JSON_CONFIGURATION_FILE: o caminho para um arquivo JSON
com os detalhes de configuração do job.
API
Faça uma solicitação POST ao
método jobs.create
que define o campo collocation como COLLOCATED.
Por exemplo, para criar um job de script básico que especifique uma
política de posicionamento compacto, faça a seguinte solicitação:
POSThttps://batch.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/jobs?job_id=JOB_NAME{"taskGroups":[{"taskSpec":{"runnables":[{"script":{"text":"echo Hello world from task ${BATCH_TASK_INDEX}"}}]},"taskCount":3}],"allocationPolicy":{"placement":{"collocation":"COLLOCATED"}},"logsPolicy":{"destination":"CLOUD_LOGGING"}}
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-09-02 UTC."],[[["\u003cp\u003eSpecifying a compact placement policy reduces network latency between a job's virtual machines (VMs) by ensuring they are located on physically closer hosts within a zone.\u003c/p\u003e\n"],["\u003cp\u003eCompact placement policies are beneficial for jobs with tightly coupled tasks, especially those that utilize MPI libraries for communication.\u003c/p\u003e\n"],["\u003cp\u003eBatch automatically creates and manages compact placement policies when specified, without the ability to use a pre-existing one or specifying the number of VMs.\u003c/p\u003e\n"],["\u003cp\u003eYou can set a compact placement policy for a job by setting the \u003ccode\u003ecollocation\u003c/code\u003e field to \u003ccode\u003eCOLLOCATED\u003c/code\u003e in the job configuration, either through the gcloud CLI or the Batch API.\u003c/p\u003e\n"],["\u003cp\u003eBefore creating a job, ensure you have the necessary permissions, which includes the Batch Job Editor role and the Service Account User role.\u003c/p\u003e\n"]]],[],null,["# Reduce latency by using compact placement policies\n\nThis document explains how to reduce network latency among a job's VMs by\nspecifying a compact placement policy.\n\nHaving VM hosts that are physically closer to each other within a\n[zone](/compute/docs/regions-zones#zones_and_clusters) can reduce\nnetwork latency between VMs. This performance benefit can be especially useful\nfor jobs with tightly coupled tasks, such as\n[tasks that communicate using MPI libraries](/batch/docs/create-run-job-mpi-library).\nWhen you create a job, you can optionally require a job's VMs to be located\ncloser to each other by specifying a compact placement policy.\nOtherwise, default VM placement typically distributes VMs across\nseparate hosts to help minimize the impact of power failures.\n\nTo learn more about compact placement policies, see\n[About placement policies](/compute/docs/instances/placement-policies-overview)\nin the Compute Engine documentation.\n\nBefore you begin\n----------------\n\n1. If you haven't used Batch before, review [Get started with Batch](/batch/docs/get-started) and enable Batch by completing the [prerequisites for projects and users](/batch/docs/get-started#prerequisites).\n2.\n\n To get the permissions that\n you need to create a job,\n\n ask your administrator to grant you the\n following IAM roles:\n\n - [Batch Job Editor](/iam/docs/roles-permissions/batch#batch.jobsEditor) (`roles/batch.jobsEditor`) on the project\n - [Service Account User](/iam/docs/roles-permissions/iam#iam.serviceAccountUser) (`roles/iam.serviceAccountUser`) on the [job's service account](/batch/docs/create-run-job-custom-service-account#create-job-service-account), which by default is the [default Compute Engine service account](/compute/docs/access/service-accounts#default_service_account)\n\n\n For more information about granting roles, see [Manage access to projects, folders, and organizations](/iam/docs/granting-changing-revoking-access).\n\n\n You might also be able to get\n the required permissions through [custom\n roles](/iam/docs/creating-custom-roles) or other [predefined\n roles](/iam/docs/roles-overview#predefined).\n\n\u003cbr /\u003e\n\nRestrictions\n------------\n\nIn addition to the\n[general restrictions for compact placement policies](/compute/docs/instances/placement-policies-overview#restrictions-compact-policies),\nBatch also has the following restrictions:\n\n- When you specify for a job to use a compact placement policy, Batch automatically creates and deletes a compact placement policy for the job's VMs. You can't specify an existing compact placement policy for a job.\n- You can't specify a number of VMs for the compact placement policy. The compact placement policy for a job applies regardless of how many VMs the job runs on.\n\nCreate and run a job that uses a placement policy\n-------------------------------------------------\n\nYou can specify for a job to use a compact placement policy by setting the\n[`collocation` field](/batch/docs/reference/rest/v1/projects.locations.jobs#PlacementPolicy.FIELDS.collocation)\nto `COLLOCATED` using the gcloud CLI or Batch API. \n\n### gcloud\n\n1. Create a JSON file that specifies the job's configuration details and sets\n the `collocation` field to `COLLOCATED`.\n\n For example, to create a basic script job that specifies a\n compact placement policy, create a JSON file with the following contents: \n\n {\n \"taskGroups\": [\n {\n \"taskSpec\": {\n \"runnables\": [\n {\n \"script\": {\n \"text\": \"echo Hello world from task ${BATCH_TASK_INDEX}\"\n }\n }\n ]\n },\n \"taskCount\": 3\n }\n ],\n \"allocationPolicy\": {\n \"placement\": {\n \"collocation\": \"COLLOCATED\"\n }\n },\n \"logsPolicy\": {\n \"destination\": \"CLOUD_LOGGING\"\n }\n }\n\n2. To create and run the job, use the\n [`gcloud batch jobs submit` command](/sdk/gcloud/reference/batch/jobs/submit):\n\n gcloud batch jobs submit \u003cvar translate=\"no\"\u003eJOB_NAME\u003c/var\u003e \\\n --location \u003cvar translate=\"no\"\u003eLOCATION\u003c/var\u003e \\\n --config \u003cvar translate=\"no\"\u003eJSON_CONFIGURATION_FILE\u003c/var\u003e\n\n Replace the following:\n - \u003cvar translate=\"no\"\u003eJOB_NAME\u003c/var\u003e: the name of the job.\n\n - \u003cvar translate=\"no\"\u003eLOCATION\u003c/var\u003e: the [location](/batch/docs/locations)\n of the job.\n\n - \u003cvar translate=\"no\"\u003eJSON_CONFIGURATION_FILE\u003c/var\u003e: the path for a JSON\n file with the job's configuration details.\n\n### API\n\nMake a `POST` request to the\n[`jobs.create` method](/batch/docs/reference/rest/v1/projects.locations.jobs/create)\nthat sets the `collocation` field to `COLLOCATED`.\n\nFor example, to create a basic script job that specifies a\ncompact placement policy, make the following request: \n\n POST https://batch.googleapis.com/v1/projects/\u003cvar translate=\"no\"\u003ePROJECT_ID\u003c/var\u003e/locations/\u003cvar translate=\"no\"\u003eLOCATION\u003c/var\u003e/jobs?job_id=\u003cvar translate=\"no\"\u003eJOB_NAME\u003c/var\u003e\n\n {\n \"taskGroups\": [\n {\n \"taskSpec\": {\n \"runnables\": [\n {\n \"script\": {\n \"text\": \"echo Hello world from task ${BATCH_TASK_INDEX}\"\n }\n }\n ]\n },\n \"taskCount\": 3\n }\n ],\n \"allocationPolicy\": {\n \"placement\": {\n \"collocation\": \"COLLOCATED\"\n }\n },\n \"logsPolicy\": {\n \"destination\": \"CLOUD_LOGGING\"\n }\n }\n\nReplace the following:\n\n- \u003cvar translate=\"no\"\u003ePROJECT_ID\u003c/var\u003e: the\n [project ID](/resource-manager/docs/creating-managing-projects#identifying_projects)\n of your project.\n\n- \u003cvar translate=\"no\"\u003eLOCATION\u003c/var\u003e: the [location](/batch/docs/locations)\n of the job.\n\n- \u003cvar translate=\"no\"\u003eJOB_NAME\u003c/var\u003e: the name of the job.\n\nWhat's next\n-----------\n\n- If you have issues creating or running a job, see [Troubleshooting](/batch/docs/troubleshooting).\n- [View jobs and tasks](/batch/docs/view-jobs-tasks).\n- Learn about more [job creation options](/batch/docs/create-run-job#job-creation-options)."]]