如何获取AWS SageMaker Notebook实例的有效运行时长?
获取AWS SageMaker Notebook实例有效运行时长与成本的正确方法
你的现有方法不准确,核心原因是LastModifiedTime记录的是实例最后一次状态变更或配置修改的时间(比如启动、停止、修改实例类型等操作都会更新该值),如果实例中途被停止过,用当前时间减去这个值计算出的时长会包含停止的时间段,无法反映真实运行时长。
正确获取运行时长的方法
方法1:通过CloudWatch指标统计运行时长
SageMaker会自动向CloudWatch推送NotebookInstanceStatus指标,当实例处于运行状态时,指标值为1,停止时为0。可以通过CloudWatch的统计接口直接累加运行时段:
import boto3 from datetime import datetime, timedelta cloudwatch = boto3.client('cloudwatch') notebook_name = "你的Notebook实例名称" # 定义查询时间范围,示例为过去30天 start_time = datetime.utcnow() - timedelta(days=30) end_time = datetime.utcnow() response = cloudwatch.get_metric_statistics( Namespace='AWS/SageMaker', MetricName='NotebookInstanceStatus', Dimensions=[ { 'Name': 'NotebookInstanceName', 'Value': notebook_name }, ], StartTime=start_time, EndTime=end_time, Period=3600, # 按小时粒度统计,可根据需求调整 Statistics=['Sum'], Unit='Count' ) # 累加所有处于运行状态的小时数 total_run_hours = sum([datapoint['Sum'] for datapoint in response['Datapoints']]) print(f"总运行时长:{total_run_hours:.2f} 小时")
方法2:通过CloudTrail追踪启停事件
如果需要精确到秒级的启停时间点,可以通过CloudTrail查询实例的StartNotebookInstance和StopNotebookInstance事件,逐个计算每次运行的时长并累加:
import boto3 from datetime import datetime cloudtrail = boto3.client('cloudtrail') notebook_name = "你的Notebook实例名称" # 查询过去30天内的启停事件 response = cloudtrail.lookup_events( LookupAttributes=[ {'AttributeKey': 'EventName', 'AttributeValue': 'StartNotebookInstance'}, {'AttributeKey': 'EventName', 'AttributeValue': 'StopNotebookInstance'} ], StartTime=datetime.utcnow() - timedelta(days=30), EndTime=datetime.utcnow() ) # 按事件时间排序,确保启停顺序正确 events = sorted(response['Events'], key=lambda x: x['EventTime']) total_run_seconds = 0 current_start_time = None for event in events: # 仅处理目标实例的事件 if event['Resources'][0]['ResourceName'] != notebook_name: continue if event['EventName'] == 'StartNotebookInstance': current_start_time = event['EventTime'] elif event['EventName'] == 'StopNotebookInstance' and current_start_time: duration = (event['EventTime'] - current_start_time).total_seconds() total_run_seconds += duration current_start_time = None # 如果实例当前仍在运行,补充最后一次启动到现在的时长 if current_start_time: total_run_seconds += (datetime.utcnow() - current_start_time).total_seconds() total_run_hours = total_run_seconds / 3600 print(f"总运行时长:{total_run_hours:.2f} 小时")
获取总成本的方法
方法1:通过Cost Explorer API查询
直接调用Cost Explorer接口,按实例ID筛选SageMaker的成本数据:
import boto3 from datetime import datetime, timedelta ce = boto3.client('ce') notebook_name = "你的Notebook实例名称" start_date = (datetime.utcnow() - timedelta(days=30)).strftime('%Y-%m-%d') end_date = datetime.utcnow().strftime('%Y-%m-%d') response = ce.get_cost_and_usage( TimePeriod={'Start': start_date, 'End': end_date}, Granularity='DAILY', Filter={ 'And': [ {'Dimensions': {'Key': 'SERVICE', 'Values': ['Amazon SageMaker']}}, {'Dimensions': {'Key': 'RESOURCE_ID', 'Values': [notebook_name]}} ] }, Metrics=['UnblendedCost'] ) # 累加每日成本得到总成本 total_cost = sum( float(day['Total']['UnblendedCost']['Amount']) for day in response['ResultsByTime'] ) print(f"总成本:${total_cost:.2f}")
方法2:运行时长 × 实例单价
如果你已知实例的每小时定价(需注意区域、实例类型、是否为预留实例等因素),可以用计算出的总运行时长直接乘以单价得到成本,建议以AWS官方定价或Cost Explorer数据为准。
内容的提问来源于stack exchange,提问作者Udara Nilupul
相关产品推荐
相关产品推荐

