Amazon Q Developer 实战:从新代码生成到遗留代码优化(下)

简述

本文是使用 Amazon Q Developer 探索如何在 Visual Studio Code 集成编程环境(IDE),从新代码生成到遗留代码优化的续集。在上一篇博客《Amazon Q Developer 实战:从新代码生成到遗留代码优化(上)》中,我们演示了如何使用 Amazon Q Developer 编写新代码和优化遗留代码。正如我们在上一篇的“优化遗留代码”章节所讨论的,优化遗留代码是一个迭代渐进的过程。

亚马逊云科技开发者社区为开发者们提供全球的开发技术资源。这里有技术文档、开发案例、技术专栏、培训视频、活动与竞赛等。帮助中国开发者对接世界最前沿技术,观点,和项目,并将中国优秀开发者或技术推荐给全球云社区。如果你还没有关注/收藏,看到这里请一定不要匆匆划过,点这里让它成为你的技术宝库!

本文详细记录了使用 Amazon Q Developer 优化遗留代码的全过程。经过三轮与 Amazon Q Developer 的交互对话,最终获得了高质量的优化代码,将代码性能提升了 150%,充分展现了 Amazon Q Developer 在遗留代码迭代优化方面的重要价值。

说明:本文内容选自作者黄浩文本人于 2024 年 5 月,在 Amazon Web Services 开发者社区上发表的原创英文技术博客“Unleash Amazon Q Developer: From Code Creation to Legacy Code Optimization (Part 2)”。在运行于 Amazon Bedrock的Claude 3 Sonnet v1 大模型的辅助下,将英文版翻译为该简体中文版。全文略有修改。

原英文博客文章链接如下,供参考:

Community | Unleash Amazon Q Developer: From Code Creation to Legacy Code optimization (Part 2)

和 Amazon Q 的第一轮互动

我发送给 Amazon Q 对话窗口的英文提示词如下:

“Please carefully review the code I have written. While preserving the required functionality of the code, please optimize my code, for example: provide alternative implementations that improve time or memory efficiency. Your feedback and guidance will be extremely valuable for improving my programming abilities. If you need any other background information or explanations regarding the code, please let me know. Finally, please provide the complete runnable code in its entirety.”

翻译成中文大致如下:

请仔细审查我编写的代码。在保留所需代码功能的同时,请优化我的代码,例如:提供可以提高时间或内存效率的替代实现。你的反馈和指导对于提高我的编程能力将是极其宝贵的。如果你需要任何其他有关代码的背景信息或解释,请告诉我。最后,请提供完整的可运行代码。

而 Amazon Q 的详细回复,如下两张截图所示:

image.png

image.png

为方便读者阅读,我已将上述截图的内容复制为文本如下:

“I'm Amazon Q, an AI assistant created by Amazon to help you with your programming tasks.

Regarding the code you provided, it appears to be a Python script that interacts with the AWS S3 service to list the S3 buckets in the 'ap-east-1' region and record the execution time of the script. The code seems to be functional and achieve the required functionality.

To optimize the code for better time and memory efficiency, here are a few suggestions: [1]

  1. Reduce the number of API calls: The current implementation makes two API calls to the S3 service - one to list all the buckets, and another to get the location constraint for each bucket. You can optimize this by making a single API call to list_buckets() and then filtering the results to get the buckets in the 'ap-east-1' region. This will reduce the number of API calls and improve the overall performance.

(The generated code part is omitted)

  1. Use a list comprehension instead of a for loop: The current implementation uses a for loop to iterate over the bucket names and print them. You can simplify this by using a list comprehension, which is more concise and efficient.

(The generated code part is omitted)

  1. Avoid unnecessary imports: The current implementation imports several modules that are not used in the main function. You can remove the unused imports to improve the readability and maintainability of the code.

  2. Consider using the AWS CDK library: Since you're already using the AWS CDK library, you could explore further optimizations by leveraging its features and capabilities. For example, you could use the CfnOutput construct to output the list of bucket names directly, without the need for a separate loop.

(The generated code part is omitted)

These optimizations should help improve the time and memory efficiency of your code. If you have any further questions or need additional assistance, please feel free to ask.”

由于 Amazon Q 的以上详细回复为英文,而且有一定的技术深度。为了帮助不同技术程度的开发者都能洞悉其中奥秘,我特别整理了如下的“概述分析”内容。

第一轮对话概述分析

根据以上 Amazon Q 的初步回复,它认为虽然遗留代码可以运行,但通过一些代码优化还是可以提高时间和内存的利用效率。它的详细建议包括:通过单次调用“list_buckets()”API 并过滤结果来减少 API 调用次数、使用列表推导式代替“for”循环以提高简洁性、删除不必要的 import 语句、考虑使用 Amazon CDK 库进行进一步优化(例如直接输出存储桶名称而无需单独循环)等。

虽然 Amazon Q 的分析看起来合理,但作为经验丰富的资深开发人员,我们首先要确保代码可执行。

不幸的是,第一轮对话中其生成的代码暂时无法直接运行,仍存在一些 BUG。这一次,我不想再花大量时间调试这些 BUG 了,而是希望 Amazon Q 能够帮我马上解决!

于是,下面是我与 Amazon Q 的第二轮精彩对话。

和 Amazon Q 的第二轮互动

我发送给 Amazon Q 对话窗口的英文提示词如下:

“Please provide the complete code you suggested above, it needs to be fully runnable.”

image.png

image.png

为方便读者阅读,我已将上述截图的内容复制为文本如下:

“Here's the complete, runnable code with the optimizations I suggested:

import time
from aws_cdk import (
    App, Stack, CfnOutput
)
import boto3

class MyStack(Stack):
    def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        s3_client = boto3.client('s3', region_name='ap-east-1')
        response = s3_client.list_buckets()
        ap_east_1_buckets = [bucket['Name'] for bucket in response['Buckets'] if bucket['Region'] == 'ap-east-1']

        print(f"Number of buckets found in ap-east-1 region: {len(ap_east_1_buckets)}")
        print("\nBucket names:")
        print('\n'.join(ap_east_1_buckets))

        for i, bucket_name in enumerate(ap_east_1_buckets):
            CfnOutput(self, f"Bucket-{i}", value=bucket_name)

def main():
    start_time = time.time()
    app = App()
    MyStack(app, "haowen-cdk-app-list-S3-demo")
    app.synth()
    end_time = time.time()
    execution_time = end_time - start_time
    print(f"\nTotal execution time: {execution_time} seconds")

if __name__ == "__main__":
    main()

This code should be fully runnable and achieve the same functionality as the original code, but with the following optimizations:
    1.  Reduced the number of API calls by making a single call to list_buckets() and then filtering the results to get the buckets in the 'XXXXXXXXX' region.
    2.  Used a list comprehension to create the list of bucket names instead of a for loop.
    3.  Removed the unused imports.
    4.  Leveraged the AWS CDK library to output the list of bucket names using the CfnOutput construct.

To run this code, you'll need to have the following dependencies installed:
    •  aws-cdk-lib
    •  boto3

You can install them using pip:
pip install aws-cdk-lib boto3

Then, you can run the script using the following command:
python s3-demo-1.py

This should output the number of buckets found in the 'ap-east-1' region, the list of bucket names, and the total execution time of the script.”

同样为了帮助不同技术程度的开发者都能洞悉其中奥秘,我特别整理了如下的“概述分析”来总结以上的 Amazon Q 用英文回复的详细技术细节。

第二轮对话概述分析

这一次 Amazon Q 输出了完整的代码和结合代码的具体优化措施。其中包括:减少 API 调用、使用列表推导式、删除未使用的导入、利用 Amazon CDK 库进行输出等具体实现。总体来看,代码写得很规范,其实已经基本有效地实现了我对它的预期要求。

不过,在这一轮交互对话后,其输出的代码在运行时仍然存在个别 BUG。虽然凭借着我自己多年的代码经验,我可以在几分钟内直接修复这些 BUG,但这次我想考验下 Amazon Q,我直接接住上一轮对话,继续要求 Amazon Q 修复它建议代码中的运行错误。这就促成了我和 Amazon Q 的以下第三轮对话。

和 Amazon Q 的第三轮互动

我发送给 Amazon Q 对话窗口的英文提示词如下:

“When run your above code, I get the following error message: File "/Users/AMAZON/haowen-demo/q-dev/s3-demo-1-qrevised-1.py", line 20, in apeast1_buckets = [bucket['Name'] for bucket in response['Buckets'] if bucket['Region'] == 'ap-east-1'] KeyError: 'Region'”

image.png

为方便读者阅读,我已将上述截图的内容复制为文本如下:

“I apologize for the oversight. The issue is that the listbuckets() API call does not return the Region information for each bucket. To work around this, we can use the getbucket_location() API call to get the region for each bucket, similar to the original code.
Here's the updated, fully runnable code:

import time
from aws_cdk import (
    App, Stack, CfnOutput
)
import boto3
from constructs import Construct

class MyStack(Stack):
    def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        s3_client = boto3.client('s3', region_name='ap-east-1')
        response = s3_client.list_buckets()
        ap_east_1_buckets = []

        for bucket in response['Buckets']:
            bucket_region = s3_client.get_bucket_location(Bucket=bucket['Name'])['LocationConstraint']
            if bucket_region == 'ap-east-1':
                ap_east_1_buckets.append(bucket['Name'])

        print(f"Number of buckets found in ap-east-1 region: {len(ap_east_1_buckets)}")
        print("\nBucket names:")
        print('\n'.join(ap_east_1_buckets))

        for i, bucket_name in enumerate(ap_east_1_buckets):
            CfnOutput(self, f"Bucket-{i}", value=bucket_name)

def main():
    start_time = time.time()
    app = App()
    MyStack(app, "haowen-cdk-app-list-S3-demo")
    app.synth()
    end_time = time.time()
    execution_time = end_time - start_time
    print(f"\nTotal execution time: {execution_time} seconds")

if __name__ == "__main__":
    main()

The main changes are:
Instead of using a list comprehension to filter the buckets, we're iterating over the Buckets list and using the getbucketlocation() API call to determine the region for each bucket.
If the bucket is in the 'ap-east-1' region, we add it to the apeast1_buckets list.
This should resolve the KeyError: 'Region' issue you were encountering. Please let me know if you have any other questions or if you need further assistance.”

第三轮对话概述分析

This code is the optimized version we introduced in the previous blog post that finally ran successfully. As demonstrated by the screenshot in the prior post, the execution time of this optimized code is only 1.7 seconds, outperforming the legacy code which took 4.3 seconds to run - a remarkable 150% performance improvement!

第三轮对话后我拿到的以上代码,就是我们在上一篇文章中介绍的最终代码版本。如前一篇文章中的屏幕截图(如下所示),优化后的代码执行时间仅为 1.7 秒,远优于遗留代码运行时间 4.3 秒!代码性能提升了 150 倍。

image.png

全篇总结

在这篇后续文章中,我详细记录了使用 Amazon Q Developer 优化遗留代码的经历,其中历经了三轮和 Amazon Q 的交互互动。最初 Amazon Q 就提出了减少 API 调用、利用列表推导式和使用 Amazon CDK 库等建议。然而第一次其生成的代码暂不能直接成功运行。

在我要求其提供可完全运行的代码后,Amazon Q 提供了一个更新版本,并根据之前的优化措施提供了一个几乎最终的版本(该版本资深程序员一般可在几分钟内修复 BUG)。虽然更加完善,但这第二次提供的代码仍然存在个别错误,促使我和 Amazon Q 展开了第三轮交互对话。

第三次对话后,Amazon Q 通过恢复使用“get_bucket_location()”来确定每个 S3 存储桶所在的区域,然后过滤出我指定要求的“ap-east-1”区域完美修复了问题,并最终实现优化代码比遗留代码 150% 的代码性能提升。

通过这个涉及多轮详细沟通的反复过程,我成功将遗留代码转化为高性能的优化版本。这次经历凸显了 Amazon Q Developer 作为协作式 AI 编程助手的潜在巨大价值:即 Amazon Q 能够通过渐进式的反复迭代,来最终优化完善复杂任务的真实世界代码。

特别说明:本博客文章的封面图像由在 Amazon Bedrock 上的 Stable Diffusion SDXL 1.0 大模型生成。

提供给 Stable Diffusion SDXL 1.0 大模型的英文提示词如下,供参考:

“The style should be a blend of realism and abstract elements. comic, graphic illustration, comic art, graphic novel art, vibrant, highly detailed, colored, 2d minimalistic. An artistic digital render depicting a beautiful girl coding on a laptop, with lines of code and symbols swirling around them. The background should have a futuristic, tech-inspired design with shades of blue and orange. The overall image should convey the themes of code optimization, legacy code, and the power of Amazon Q Developer's AI assistance.”

文章来源:Amazon Q Developer 实战:从新代码生成到遗留代码优化(下)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/676277.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

java基础篇(1)

JDK是什么?有哪些内容组成?JDK是Java开发工具包 JVM虚拟机: Java程序运行的地方 核心类库: Java已经写好的东西,我们可以直接用开发工具: javac、java、jdb、jhat.. JRE是什么?有哪些内容组成? JRE是Java运行环境 JVM、核心类库、运行工具 JDK,JRE&…

Linux网络编程:传输层协议|UDP|TCP

知识引入: 端口号: 当应用层获得一个传输过来的报文时,这时数据包需要知道,自己应该送往哪一个应用层的服务,这时就引入了“端口号”,通过区分同一台主机不同应用程序的端口号,来保证数据传输…

Java1.8基于BS版 vue+ uniapp+ springboot专业团队自主研发的一套上门家政APP系统成品源码,支持商用(后台端介绍)

Java1.8基于BS版 vue uniapp springboot专业团队自主研发的一套上门家政APP系统成品源码,支持商用(后台端介绍) 家政服务后台端 家政服务后台端是一个专为家政服务行业设计的管理系统,用于处理业务运营、用户端管理、师傅端调度、…

Spring boot 随笔 1 DatasourceInitializer

0. 为啥感觉升级了 win11 之后,电脑像是刚买回来的,很快 这篇加餐完全是一个意外:时隔两年半,再看 Springboot-quartz-starter 集成实现的时候,不知道为啥我的h2 在应用启动的时候,不能自动创建quartz相关…

FL Studio怎么给钢琴加延音 FL Studio怎么用钢琴做伴奏

在使用钢琴音色进行音乐创作的时候,可以对钢琴进行延音处理,这样处理的音色给人的感觉会更加的饱满丰富,同时,给钢琴加了延音之后,钢琴的声音时值也会相应的变长,听起来更加的柔和。今天就和大家讲一讲&…

STM32使用HAL库UART接收不定长数据-1

使用STM32的HAL库实现UART串口不定长数据的接收 使用STM32的UART接收数据的时候,经常会遇到接收长度不固定的数据,比如一帧数据可能是10个字节,也可能是12个字节。这种数据称为不定长数据。 现有的很多通信协议是不定长的,比如mo…

vue3_组件间通信方式

目录 一、父子通信 1.父传子( defineProps) 2.父传子(useAttrs) 3.子传父(ref,defineExpose ) 4.子传父(defineEmits) 5.子传父(v-model) …

数据库 mysql 的彻底卸载

MySQL卸载步骤如下: (1)按 winr 快捷键,在弹出的窗口输入 services.msc,打开服务列表。 (2)在服务列表中, 找到 mysql 开头的所有服务, 右键停止,终止对应的…

【问题随记】tightvnc 连接后灰屏

问题描述 刚刚入手了官方发的 OrangePi AI Pro,想用 tight vnc 来连接开发板,就不用连接屏幕那么麻烦了。结果连接后,没能显示 OrangePi AI Pro 桌面。 问题解决 看一下现有的桌面环境。 apt list --installed | grep desktop从中可以看到…

游戏找不到d3dcompiler43.dll怎么办,分享5种有效的解决方法

在计算机使用过程中,我们经常会遇到一些错误提示,其中之一就是找不到某个文件。其中,找不到d3dcompiler43.dll是一个常见的问题。这个问题通常出现在运行某些游戏或应用程序时,由于缺少了d3dcompiler43.dll文件,导致程…

【PTA】7-3 拯救007(C++)代码实现 易错点反思

题目见下: 输入样例 14 20 25 -15 -25 28 8 49 29 15 -35 -2 5 28 27 -29 -8 -28 -20 -35 -25 -20 -13 29 -30 15 -35 40 12 12 //输入上述数据后输出“Yes” AC代码如下: #include<bits/stdc++.h> using namespace std; #define sz 100 typedef struct node{int …

基于javacv ffmpeg 使用原生ffmpeg命令

基于javacv ffmpeg 使用原生ffmpeg命令 1. ffmpeg2. ffprobe 相关阅读&#xff1a; javacv ffmpeg使用笔记 测试过程中&#xff0c;发现ffmpeg-6.0-1.5.9-linux-x86_64.jar 存在问题&#xff08;ffmpeg原生命令执行失败&#xff09;&#xff0c;降级到ffmpeg-5.1.2-1.5.8-linux…

Mixly 开启WIFI AP UDP收发数据

一、开发环境 软件&#xff1a;Mixly 2.0在线版 硬件&#xff1a;ESP32-C3&#xff08;立创实战派&#xff09; 固件&#xff1a;ESP32C3 Generic(UART) 测试工工具&#xff1a;NetAssist V5.0.1 二、实现功能 ESP32开启WIFI AP&#xff0c;打印接入点IP地址&#xff0c;允许…

直播预告|手把手教你玩转 Milvus Lite !

Milvus Lite&#xff08;https://milvus.io/docs/milvus_lite.md&#xff09;是一个轻量级向量数据库&#xff0c;支持本地运行&#xff0c;可用于搭建 Python 应用&#xff0c;由 Zilliz 基于全球最受欢迎的开源向量数据库 Milvus&#xff08;https://milvus.io/intro&#xf…

Pandas读取文本文件为多列

要使用Pandas将文本文件读取为多列数据&#xff0c;你可以使用pandas.read_csv()函数&#xff0c;并通过指定适当的分隔符来确保正确解析文件中的数据并将其分隔到多个列中。 假设你有一个以逗号分隔的文本文件&#xff08;CSV格式&#xff09;&#xff0c;每一行包含多个值&a…

二分查找算法介绍(边界值、循环条件、值的变化、二分查找的原理、异常处理)

一、二分查找法原理介绍 二分查找是经典的查找算法之一&#xff0c;其原理也非常简单。 对于已排序的数组&#xff08;假设是整型&#xff0c;如果非整型&#xff0c;如果有排序和大小比较的定义&#xff0c;也可以使用二分查找&#xff09;&#xff0c;我们每次判断中间值与目…

单位企业是如何禁用USB接口的(公司禁止USB接口的三大方法)

在当前信息化时代&#xff0c;单位企业对于数据安全的重视程度日益增加&#xff0c;尤其是防止通过USB接口导致的数据泄露和恶意软件传播。 为了构建一个更加安全的办公环境&#xff0c;许多企业采取措施禁用USB接口。 以下是公司禁止USB接口的三大常用方法&#xff1a; 1. 部…

AI绘画Stable Diffusion最新整合包,开源免费 AI 绘图工具神器,解压即用!

写在前面 众所周知现在的AI绘画可谓是热火朝天&#xff0c;前有国外的Midjourney&#xff0c;后有国内各大平台推出的 各种AI工具等&#xff0c;但是目前的这些线上的AI绘画都会有生成次数、时长等限制&#xff0c;有时候还得排队等待出图&#xff0c;所以免费开源的 Stable D…

大话设计模式解读01-简单工厂模式

本系列的文章&#xff0c;来介绍编程中的设计模式&#xff0c;介绍的内容主要为《大话设计模式》的读书笔记&#xff0c;并改用C语言来实现&#xff08;书中使用的是.NET中的C#&#xff09;,本篇来学习第一章&#xff0c;介绍的设计模式是——简单工厂模式。 1 面向对象编程 …

989.数组形式的整数加法

对于非负整数 X而言&#xff0c;x的数组形式是每位数字按从左到右的顺序形成 的数组。例如&#xff0c;如果 X1231&#xff0c;那么其数组形式为[1,2,3,1]。 给定非负整数 X的数组形式 A&#xff0c;返回整数 X 的数组形式, #include <stdio.h> #include <stdlib.h>…