Skip to content

Commit

Permalink
perf: Optimize average_time_cost calculation in job model
Browse files Browse the repository at this point in the history
  • Loading branch information
w940853815 authored and BaiJiangJie committed Jan 13, 2025
1 parent 583486e commit eafb5ec
Showing 1 changed file with 13 additions and 6 deletions.
19 changes: 13 additions & 6 deletions apps/ops/models/job.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
from celery import current_task
from django.conf import settings
from django.db import models
from django.db.models import Q
from django.db.models import Q, Avg, F, FloatField
from django.db.models.functions import Coalesce, Now, Extract
from django.utils import timezone
from django.utils.translation import gettext_lazy as _

Expand Down Expand Up @@ -188,11 +189,17 @@ def summary(self):

@property
def average_time_cost(self):
total_cost = 0
finished_count = self.executions.filter(status__in=['success', 'failed']).count()
for execution in self.executions.filter(status__in=['success', 'failed']).all():
total_cost += execution.time_cost
return total_cost / finished_count if finished_count else 0
executions = self.executions.filter(status__in=['success', 'failed'])
if not executions.exists():
return 0
average = executions.annotate(
time_cost=Coalesce(F('date_finished'), Now()) - F('date_start')
).annotate(
time_cost_seconds=Extract('time_cost', 'epoch')
).aggregate(
avg_time=Avg('time_cost_seconds')
)['avg_time']
return average if average is not None else 0

def get_register_task(self):
from ..tasks import run_ops_job
Expand Down

0 comments on commit eafb5ec

Please sign in to comment.