估算消耗计划成本Estimating Consumption plan costs

对于在 Azure Functions 中运行的应用,目前有三种类型的托管计划,每种计划都有自己的定价模型:There are currently three types of hosting plans for an app that runs in Azure Functions, with each plan having its own pricing model:

计划Plan 说明Description
消耗Consumption 只根据函数应用的运行时间收费。You're only charged for the time that your function app runs. 此计划包括基于订阅的免费授予This plan includes a free grant on a per subscription basis.
专用(应用服务) Dedicated (App Service)
(基本或更高层)(basic tier or higher)
需要在专用 VM 或隔离的环境中运行、自定义映像,或想要使用超额的应用服务计划容量时。When you need to run in dedicated VMs or in isolation, use custom images, or want to use your excess App Service plan capacity. 使用常规应用服务计划计费Uses regular App Service plan billing. 成本取决于所选的定价层。Cost is based on your chosen pricing tier.

选择对函数性能和成本要求最有利的计划。You chose the plan that best supports your function performance and cost requirements. 若要了解详细信息,请参阅 Azure Functions 的缩放和托管To learn more, see Azure Functions scale and hosting.

本文仅涉及到消耗计划,因为此计划产生可变的成本。This article deals only with the Consumption plan, since this plan results in variable costs. 本文将取代消耗计划成本计费常见问题解答一文。This article supersedes the Consumption plan cost billing FAQ article.

Durable Functions 也可以在消耗计划中运行。Durable Functions can also run in a Consumption plan. 若要详细了解使用 Durable Functions 时的成本注意事项,请参阅 Durable Functions 计费To learn more about the cost considerations when using Durable Functions, see Durable Functions billing.

消耗计划成本Consumption plan costs

单个函数执行的执行成本以“GB 秒”来度量。 The execution cost of a single function execution is measured in GB-seconds. 执行成本是通过将其内存用量与执行时间相结合计算得出的。Execution cost is calculated by combining its memory usage with its execution time. 函数的运行时间越长,其成本越高;同理,函数消耗的内存越多,其成本越高。A function that runs for longer costs more, as does a function that consumes more memory.

假设函数使用的内存量保持恒定。Consider a case where the amount of memory used by the function stays constant. 在这种情况下,进行简单的相乘即可计算成本。In this case, calculating the cost is simple multiplication. 例如,假设函数运行了 3 秒,消耗了 0.5 GB。For example, say that your function consumed 0.5 GB for 3 seconds. 那么,执行成本为 0.5GB * 3s = 1.5 GB-secondsThen the execution cost is 0.5GB * 3s = 1.5 GB-seconds.

由于内存用量会不断变化,计算结果实质上是不同时间的内存用量的积分。Since memory usage changes over time, the calculation is essentially the integral of memory usage over time. 进行这种计算时,系统会按固定的时间间隔对进程(及其子进程)的内存用量采样。The system does this calculation by sampling the memory usage of the process (along with child processes) at regular intervals. 定价页中所述,内存用量将向上舍入到最近似的 128-MB 桶。As mentioned on the pricing page, memory usage is rounded up to the nearest 128-MB bucket. 如果进程使用 160 MB,则你需要按 256 MB 的用量付费。When your process is using 160 MB, you're charged for 256 MB. 计算中会考虑并发性,即,同一进程中的多个并发函数执行。The calculation takes into account concurrency, which is multiple concurrent function executions in the same process.

备注

尽管执行成本中不直接考虑 CPU 用量,但如果该用量会影响函数的执行时间,则也会影响成本。While CPU usage isn't directly considered in execution cost, it can have an impact on the cost when it affects the execution time of the function.

对于 HTTP 触发的函数,在函数代码开始执行之前发生错误时,不会收取执行费用。For an HTTP-triggered function, when an error occurs before your function code begins to execute you aren't charged for an execution. 这意味着由于 API 密钥验证或应用服务身份验证/授权功能,来自平台的 401 响应不会计入你的执行成本。This means that 401 responses from the platform due to API key validation or the App Service Authentication / Authorization feature don't count against your execution cost. 同样,在函数处理请求之前,5xx 状态代码响应在平台中发生时不会计入成本。Similarly, 5xx status code responses aren't counted when they occur in the platform prior to a function processing the request. 在函数代码开始执行后,平台生成的 5xx 响应仍算作执行,即使函数代码未引发错误。A 5xx response generated by the platform after your function code has started to execute is still counted as an execution, even if the error isn't raised by your function code.

在估算任何计划中运行函数的总体成本时,请记住,函数运行时将使用其他多个 Azure 服务,而每个服务单独计费。When estimating the overall cost of running your functions in any plan, remember that the Functions runtime uses several other Azure services, which are each billed separately. 计算函数应用的定价时,对于与其他 Azure 服务集成的任何触发器和绑定,需要创建这些附加的服务并为其付费。When calculating pricing for function apps, any triggers and bindings you have that integrate with other Azure services require you to create and pay for those additional services.

对于在消耗计划中运行的函数,总成本是函数的执行成本加上带宽和附加服务的成本。For functions running in a Consumption plan, the total cost is the execution cost of your functions, plus the cost of bandwidth and additional services.

估算函数应用和相关服务的总体成本时,请使用 Azure 定价计算器When estimating the overall costs of your function app and related services, use the Azure pricing calculator.

相关成本Related cost 描述Description
存储帐户Storage account 需要为每个函数应用提供一个关联的常规用途 Azure 存储帐户,该帐户单独计费Each function app requires that you have an associated General Purpose Azure Storage account, which is billed separately. 函数运行时在内部使用此帐户,但你也可以将其用于存储触发器和绑定。This account is used internally by the Functions runtime, but you can also use it for Storage triggers and bindings. 如果你没有存储帐户,系统会在创建函数应用时创建一个存储帐户。If you don't have a storage account, one is created for you when the function app is created. 有关详细信息,请参阅存储帐户要求To learn more, see Storage account requirements.
Application InsightsApplication Insights 函数依靠 Application Insights 为函数应用提供高性能的监视体验。Functions relies on Application Insights to provide a high-performance monitoring experience for your function apps. 虽然未强制要求,但你应启用 Application Insights 集成While not required, you should enable Application Insights integration. 每月会免费授予遥测数据。A free grant of telemetry data is included every month. 要了解详细信息,请参阅 Azure Monitor 定价页To learn more, see the Azure Monitor pricing page.
网络带宽Network bandwidth 无需为同一区域中的 Azure 服务之间的数据传输付费。You don't pay for data transfer between Azure services in the same region. 但是,将数据出站传输到另一区域或 Azure 外部可能会产生费用。However, you can incur costs for outbound data transfers to another region or outside of Azure. 有关详细信息,请参阅带宽定价详细信息To learn more, see Bandwidth pricing details.

影响执行时间的行为Behaviors affecting execution time

函数的以下行为可能会影响执行时间:The following behaviors of your functions can impact the execution time:

  • 触发器和绑定:从函数绑定读取输入以及向其写入输出所花费的时间计为执行时间。Triggers and bindings: The time taken to read input from and write output to your function bindings is counted as execution time. 例如,如果函数使用某个输出绑定将消息写入 Azure 存储队列,则执行时间包括将该消息写入该队列所花费的时间,而函数成本计算包括该写入时间。For example, when your function uses an output binding to write a message to an Azure storage queue, your execution time includes the time taken to write the message to the queue, which is included in the calculation of the function cost.

  • 异步执行:函数等待异步请求(在 C# 中为 await)结果的时间计为执行时间。Asynchronous execution: The time that your function waits for the results of an async request (await in C#) is counted as execution time. “GB 秒”计算基于函数的开始和结束时间,以及该时间段内的内存用量。The GB-second calculation is based on the start and end time of the function and the memory usage over that period. 计算中不考虑该时间段内发生的 CPU 活动。What is happening over that time in terms of CPU activity isn't factored into the calculation. 也许可以使用 Durable Functions 来降低异步操作期间产生的成本。You may be able to reduce costs during asynchronous operations by using Durable Functions. 业务流程协调程序函数中的等待时间不产生费用。You're not billed for time spent at awaits in orchestrator functions.

查看执行数据View execution data

若要更好地了解函数对成本的影响,可以使用 Azure Monitor 查看函数应用当前生成的成本相关指标。To better understand the cost impact of your functions, you can use Azure Monitor to view cost-related metrics currently being generated by your function apps. 可以使用 Azure 门户中的 Azure Monitor 指标资源管理器或使用 REST API 来获取此数据。You can use either Azure Monitor metrics explorer in the Azure portal or REST APIs to get this data.

Monitor 指标资源管理器Monitor metrics explorer

使用 Azure Monitor 指标资源管理器可以图形格式查看消耗计划函数应用的成本相关数据。Use Azure Monitor metrics explorer to view cost-related data for your Consumption plan function apps in a graphical format.

  1. Azure 门户顶部的“搜索服务、资源和文档”中搜索 monitor,然后选择“服务”下的“Monitor”。At the top of the Azure portal in Search services, resources, and docs search for monitor and select Monitor under Services.

  2. 在左侧选择“指标” > “选择资源”,然后使用图像下方的设置选择你的函数应用。 At the left, select Metrics > Select a resource, then use the settings below the image to choose your function app.

    选择函数应用资源

    设置Setting 建议的值Suggested value 说明Description
    订阅Subscription 订阅Your subscription 包含你的函数应用的订阅。The subscription with your function app.
    资源组Resource group 你的资源组Your resource group 包含你的函数应用的资源组。The resource group that contains your function app.
    资源类型Resource type 应用服务App Services 函数应用将作为应用服务实例显示在 Monitor 中。Function apps are shown as App Services instances in Monitor.
    资源Resource 你的函数应用Your function app 要监视的函数应用。The function app to monitor.
  3. 选择“应用”以选择你的函数应用作为要监视的资源。Select Apply to choose your function app as the resource to monitor.

  4. 在“指标”中,为“聚合”选择“函数执行计数”和“求和”。From Metric, choose Function Execution Count and Sum for Aggregation. 这会在图表中将所选时间段内的执行计数之和相加。This adds the sum of the execution counts during chosen period to the chart.

    定义要添加到图表中的函数应用指标

  5. 选择“添加指标”并重复步骤 2-4,将“函数执行单位”添加到图表中。Select Add metric and repeat steps 2-4 to add Function Execution Units to the chart.

生成的图表包含所选时间范围内(在本例中为 2 小时)两个执行指标的总和。The resulting chart contains the totals for both execution metrics in the chosen time range, which in this case is two hours.

函数执行计数和执行单位图表

由于执行单位数远远大于执行计数,因此图表只显示执行单位。As the number of execution units is so much greater than the execution count, the chart just shows execution units.

此图显示两小时时间段内总共消耗了 11.1 亿个 Function Execution Units(以“MB 毫秒”度量)。This chart shows a total of 1.11 billion Function Execution Units consumed in a two-hour period, measured in MB-milliseconds. 若要转换为 GB 秒,请除以 1024000。To convert to GB-seconds, divide by 1024000. 在此示例中,函数应用消耗了 1110000000 / 1024000 = 1083.98 GB 秒。In this example, the function app consumed 1110000000 / 1024000 = 1083.98 GB-seconds. 可将此值乘以 Functions 定价页上的当前执行时间价格,得出这两个小时的成本(假设已用完了所有免费授予的执行时间)。You can take this value and multiply by the current price of execution time on the Functions pricing page, which gives you the cost of these two hours, assuming you've already used any free grants of execution time.

Azure CLIAzure CLI

Azure CLI 提供了用于检索指标的命令。The Azure CLI has commands for retrieving metrics. 可以从本地命令环境使用 CLI。You can use the CLI from a local command environment. 例如,以下 az monitor metrics list 命令返回以前使用的同一时间段内的每小时数据。For example, the following az monitor metrics list command returns hourly data over same time period used before.

请务必将 <AZURE_SUBSCRIPTON_ID> 替换为运行该命令的 Azure 订阅 ID。Make sure to replace <AZURE_SUBSCRIPTON_ID> with your Azure subscription ID running the command.

az monitor metrics list --resource /subscriptions/<AZURE_SUBSCRIPTION_ID>/resourceGroups/metrics-testing-consumption/providers/Microsoft.Web/sites/metrics-testing-consumption --metric FunctionExecutionUnits,FunctionExecutionCount --aggregation Total --interval PT1H --start-time 2019-09-11T21:46:00Z --end-time 2019-09-11T23:18:00Z

此命令返回类似于以下示例的 JSON 有效负载:This command returns a JSON payload that looks like the following example:

{
  "cost": 0.0,
  "interval": "1:00:00",
  "namespace": "Microsoft.Web/sites",
  "resourceregion": "chinanorth",
  "timespan": "2019-09-11T21:46:00Z/2019-09-11T23:18:00Z",
  "value": [
    {
      "id": "/subscriptions/XXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXX/resourceGroups/metrics-testing-consumption/providers/Microsoft.Web/sites/metrics-testing-consumption/providers/Microsoft.Insights/metrics/FunctionExecutionUnits",
      "name": {
        "localizedValue": "Function Execution Units",
        "value": "FunctionExecutionUnits"
      },
      "resourceGroup": "metrics-testing-consumption",
      "timeseries": [
        {
          "data": [
            {
              "average": null,
              "count": null,
              "maximum": null,
              "minimum": null,
              "timeStamp": "2019-09-11T21:46:00+00:00",
              "total": 793294592.0
            },
            {
              "average": null,
              "count": null,
              "maximum": null,
              "minimum": null,
              "timeStamp": "2019-09-11T22:46:00+00:00",
              "total": 316576256.0
            }
          ],
          "metadatavalues": []
        }
      ],
      "type": "Microsoft.Insights/metrics",
      "unit": "Count"
    },
    {
      "id": "/subscriptions/XXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXX/resourceGroups/metrics-testing-consumption/providers/Microsoft.Web/sites/metrics-testing-consumption/providers/Microsoft.Insights/metrics/FunctionExecutionCount",
      "name": {
        "localizedValue": "Function Execution Count",
        "value": "FunctionExecutionCount"
      },
      "resourceGroup": "metrics-testing-consumption",
      "timeseries": [
        {
          "data": [
            {
              "average": null,
              "count": null,
              "maximum": null,
              "minimum": null,
              "timeStamp": "2019-09-11T21:46:00+00:00",
              "total": 33538.0
            },
            {
              "average": null,
              "count": null,
              "maximum": null,
              "minimum": null,
              "timeStamp": "2019-09-11T22:46:00+00:00",
              "total": 13040.0
            }
          ],
          "metadatavalues": []
        }
      ],
      "type": "Microsoft.Insights/metrics",
      "unit": "Count"
    }
  ]
}

此特定响应显示,从 2019-09-11T21:462019-09-11T23:18,应用消耗了 1110000000 MB 毫秒(1083.98 GB 秒)。This particular response shows that from 2019-09-11T21:46 to 2019-09-11T23:18, the app consumed 1110000000 MB-milliseconds (1083.98 GB-seconds).

确定内存用量Determine memory usage

函数执行单位是执行时间与内存用量的组合,因此很难使用此指标来了解内存用量。Function execution units are a combination of execution time and your memory usage, which makes it a difficult metric for understanding memory usage. 目前无法通过 Azure Monitor 获取内存数据这一指标。Memory data isn't a metric currently available through Azure Monitor. 但是,如果要优化应用的内存用量,可以使用 Application Insights 收集的性能计数器数据。However, if you want to optimize the memory usage of your app, can use the performance counter data collected by Application Insights.

如果尚未执行此操作,你可以在函数应用中启用 Application InsightsIf you haven't already done so, enable Application Insights in your function app. 启用此集成后,你可以在门户中查询此遥测数据With this integration enabled, you can query this telemetry data in the portal.

在“监视”下选择“日志(分析)”,复制以下遥测查询并将其粘贴到查询窗口中,然后选择“运行”。Under Monitoring, select Logs (Analytics), then copy the following telemetry query and paste it into the query window and select Run. 此查询返回每个采样时间的总内存用量。This query returns the total memory usage at each sampled time.

performanceCounters
| where name == "Private Bytes"
| project timestamp, name, value

结果类似于以下示例:The results look like the following example:

时间戳 [UTC]timestamp [UTC] namename value
9/12/2019, 1:05:14.947 AM9/12/2019, 1:05:14.947 AM 专用字节数Private Bytes 209,932,288209,932,288
9/12/2019, 1:06:14.994 AM9/12/2019, 1:06:14.994 AM 专用字节数Private Bytes 212,189,184212,189,184
9/12/2019, 1:06:30.010 AM9/12/2019, 1:06:30.010 AM 专用字节数Private Bytes 231,714,816231,714,816
9/12/2019, 1:07:15.040 AM9/12/2019, 1:07:15.040 AM 专用字节数Private Bytes 210,591,744210,591,744
9/12/2019, 1:12:16.285 AM9/12/2019, 1:12:16.285 AM 专用字节数Private Bytes 216,285,184216,285,184
9/12/2019, 1:12:31.376 AM9/12/2019, 1:12:31.376 AM 专用字节数Private Bytes 235,806,720235,806,720

函数级指标Function-level metrics

Azure Monitor 可跟踪资源级指标,对于函数来说,就是跟踪函数应用指标。Azure Monitor tracks metrics at the resource level, which for Functions is the function app. Application Insights 集成会发出每个函数的指标。Application Insights integration emits metrics on a per-function basis. 下面是一个示例分析查询,可用于获取函数的平均持续时间:Here's an example analytics query to get the average duration of a function:

customMetrics
| where name contains "Duration"
| extend averageDuration = valueSum / valueCount
| summarize averageDurationMilliseconds=avg(averageDuration) by name
namename averageDurationMillisecondsaverageDurationMilliseconds
QueueTrigger AvgDurationMsQueueTrigger AvgDurationMs 16.08716.087
QueueTrigger MaxDurationMsQueueTrigger MaxDurationMs 90.24990.249
QueueTrigger MinDurationMsQueueTrigger MinDurationMs 8.5228.522

后续步骤Next steps