Skip to main content
 首页 » 编程设计

python之如何在速度方面提高我的 'for' 循环性能

2025年05月04日11leader

我有一个 for 循环,迭代 6907 行需要将近 20 秒。该循环完成了在给定查询集中制作唯一区域名称列表的工作。 我在代码的不同地方放置了时间戳来记录时间。花费更多时间的“for”循环位于变量“t3”和“t4”之间。

时间戳

t = 12:27:22:169533 
t2 = 12:27:22:173535 
t3 = 12:27:22:793567 
6907 
t4 = 12:27:42:907362 
t5 = 12:27:43:242596 
t6 = 12:27:43:242596 

6907 是我的查询集 sales_data 的长度

View .py

class MSZoneProduct(generic.TemplateView): 
    template_name = 'sales/MSZoneProduct.html' 
    form_class = MSZoneProductForm 
 
    def get(self, request, *args, **kwargs): 
        if request.user.is_authenticated: 
            form = self.form_class(request.GET) 
            context = {'form': form} 
            if form.is_valid(): 
                zone_code_ = form.cleaned_data['zone_name'] 
                product_code_ = form.cleaned_data['product_name'] 
 
                t = datetime.now().strftime('%H:%M:%S:%f') 
                print("t = " + t) 
                product = Product.objects.get(product_code=product_code_) 
                t2 = datetime.now().strftime('%H:%M:%S:%f') 
                print("t2 = " + t2) 
                sales_data = Sales.objects.filter(zone_code=zone_code_, product_code=product).select_related() 
                t3 = datetime.now().strftime('%H:%M:%S:%f') 
                print("t3 = " + t3) 
                print(len(sales_data)) 
                regions = [] 
                message = "" 
                regions_dict = {} 
                for x in sales_data: 
                    if x.region_name not in regions: 
                        regions.append(x.region_name) 
                    else: 
                        continue 
                t4 = datetime.now().strftime('%H:%M:%S:%f') 
                print("t4 = " + t4) 
                for x in regions: 
                    sum_ = 0 
                    for y in sales_data: 
                        if y.region_name == x: 
                            sum_ = sum_ + y.quantity 
                    regions_dict[x] = sum_ 
                t5 = datetime.now().strftime('%H:%M:%S:%f') 
                print("t5 = " + t5) 
                if len(regions) == 0: 
                    message = "There is no data available for this product in this particular region." 
 
                context = {'form': form, 'message': message, 'data': regions_dict} 
                t6 = datetime.now().strftime('%H:%M:%S:%f') 
                print("t6 = " + t6) 
                return render(request, 'sales/MSZoneProduct.html', context) 
 
            return render(request, 'sales/MSZoneProduct.html', context) 
        else: 
            return redirect('/sales/') 

请您参考如下方法:

根据您的观点,您想要汇总每个区域的数量。我们可以将所有这些逻辑移动到数据库查询中。这不仅会使它更高效,而且也更优雅:

from django.db.models import Sum 
 
sales_data = Sales.objects.filter( 
    zone_code=zone_code_, product_code=product 
).values('region_name').annotate( 
    total_quantity=Sum('quantity') 
).order_by('region_name') 

这将生成一个 QuerySet,其中包含具有两个元素的字典:'region_name' 映射到区域名称,以及 total_quantity 汇总了该地区的数量。

接下来我们可以将它转换为字典regions_dict:

regions_dict = { r['region_name']: r['total_quantity'] for r in sales_data }