Friday, December 1, 2023
HomeVideo EditingOptimizing Code With ChatGPT

Optimizing Code With ChatGPT


Anybody who has been writing code for some time is aware of how essential it’s to jot down code that’s optimized. I’m certain you will have encountered conditions the place you wrote a script that was taking a very long time to execute and needed to optimize it in order that it ran quicker.

Optimization would not all the time need to imply that the code executes quicker. You may also wish to optimize for reminiscence utilization if you’re quick on reminiscence. Equally, you may wish to optimize for utilization of some other sources, code maintainability, and so on.

On this tutorial, I’ll present you use ChatGPT to optimize your code.

Why Optimize Code?

There are a number of the explanation why you may wish to optimize code. The plain one is improved efficiency. Any script that executes rapidly will lead to value financial savings for you, in addition to a greater expertise to your customers.

Optimized code can be going to be scalable. For instance, I as soon as wrote some code that saved instantiating a brand new object till the duty at hand was achieved. This could typically lead to “out of reminiscence” errors.

One resolution was simply to extend the reminiscence restrict. It labored for some time. Nevertheless, I used to be out of reminiscence as soon as once more after I was making an attempt to unravel larger issues. Inefficient code goes to expire of sources ultimately.

In my case, I rewrote the code and ended up with a reminiscence utilization of some MB as an alternative of 4GB.

Utilizing ChatGPT for Code Optimization

Up to now, we needed to depend on different individuals from web sites like Stack Overflow to assist us optimize our code and resolve some other points that we could be going through. There isn’t a denying that Stack Overflow and different such communities are nonetheless invaluable if you wish to get work out resolve an advanced drawback. Nevertheless, now you can additionally begin utilizing ChatGPT to realize some perception into your issues and optimize the code.

Considered one of its largest benefits is that ChatGPT offers you an on the spot response. It has additionally been educated on a considerable amount of information, so it has a good data of programming ideas and greatest practices to comply with.

Optimizing the Code for Velocity

On this part, you’ll learn the way we are able to optimize our code for pace utilizing ChatGPT. We are going to use Downside 10 from Venture Euler as our instance. It states that:

The sum of the primes beneath 10 is 2+3+5+7=17.

Discover the sum of all of the primes beneath two million.

Trying on the drawback, we all know that we have to discover all of the primes beneath 2 million earlier than we are able to calculate their sum. We are going to create an array to retailer the primes. We may also want to make use of two for loops. The outer one will iterate from 2 to 2 million. The inside loop will test if any of these numbers are prime.

Right here is the code that I’ve written to do that in JavaScript:

1
let primes = [];
2

3
perform find_primes_in_range(min, max) {
4
    for(let i = min; i <= max; i++) {
5
        let is_prime = true;
6
        for(let j = 2; j <= i/2; j++) {
7
            if(i%j == 0) {
8
                is_prime = false;
9
                break;
10
            }
11
        }
12

13
        if(is_prime) {
14
            primes.push(i);
15
        }
16
    }
17
}
18

19
let begin = Date.now();
20

21
find_primes_in_range(2, 2000000);
22

23
let sum = 0;
24

25
for(let i = 0; i < primes.size; i++) {
26
    sum += primes[i];
27
}
28

29
// Output: Sum of Primes: 142913828922
30
console.log(`Sum of Primes: ${sum}`);
31

32
let finish = Date.now();
33

34
let seconds = (finish - begin)/1000;
35

36
// Output: Complete Time: 201.489
37
console.log(`Complete Time: ${seconds}`);

Our algorithm for calculating the sum of primes is relatively primitive and takes over 200 seconds. Let’s have a look at if ChatGPT can enhance it in any method.

Add the next immediate in ChatGPT, after which place your code beneath the immediate:

1
How can I optimize the JavaScript code beneath in order that it runs rapidly? It's presupposed to calculate the sum of all primes beneath two million.

ChatGPT suggests two issues that we are able to do to ensure our code executes quicker.

optimize the prime generating codeoptimize the prime generating codeoptimize the prime generating code

First, it tells us to optimize the prime-checking algorithm in order that we solely iterate as much as Math.sqrt(i) within the inside loop. Second, it advocates for the usage of the Sieve of Eratosthenes. It really works by marking all of the multiples of a primary quantity as a composite. The one numbers left on the finish are primes.

1
perform sumPrimesBelow(n) {
2
    let primes = [];
3
    let isPrime = Array(n).fill(true);
4
    let sum = 0;
5

6
    for (let i = 2; i < n; i++) {
7
        if (isPrime[i]) {
8
            primes.push(i);
9
            sum += i;
10

11
            for (let j = i * i; j < n; j += i) {
12
                isPrime[j] = false;
13
            }
14
        }
15
    }
16

17
    return sum;
18
}
19

20
let begin = Date.now();
21
let sum = sumPrimesBelow(2000000);
22
let finish = Date.now();
23

24
// Output: Sum of Primes: 142913828922
25
console.log(`Sum of Primes: ${sum}`);
26

27
// Output: Complete Time: 0.049 seconds
28
console.log(`Complete Time: ${(finish - begin) / 1000} seconds`);

The working time of our script has improved considerably. It’s round 4,000 occasions quicker.

Optimizing the Code for Reminiscence

Our unique model of the code to calculate the sum of primes saved all of them in an array, which consumes reminiscence. We will keep away from creating an array by merely calculating the working sum of the primes. As quickly as we all know {that a} quantity is prime, we add it to our present sum.

1
Are you able to optimize this JavaScript code in order that it makes use of the least attainable quantity of reminiscence?

Right here is the output that I acquired:

1
perform sumPrimesBelow(n) {
2
    let sum = 0;
3

4
    for (let i = 2; i < n; i++) {
5
        let isPrime = true;
6

7
        for (let j = 2; j <= Math.sqrt(i); j++) {
8
            if (i % j === 0) {
9
                isPrime = false;
10
                break;
11
            }
12
        }
13

14
        if (isPrime) {
15
            sum += i;
16
        }
17
    }
18

19
    return sum;
20
}
21

22
let begin = Date.now();
23
let sum = sumPrimesBelow(2000000);
24
let finish = Date.now();
25

26
// Output: Sum of Primes: 142913828922
27
console.log(`Sum of Primes: ${sum}`);
28

29
// Output: Complete Time: 0.53 seconds
30
console.log(`Complete Time: ${(finish - begin) / 1000} seconds`);

This time, we’ve traded a few of our pace for much less reminiscence utilization. The script now takes 0.5 seconds to execute, which is 10 occasions slower than utilizing the Sieve of Eratosthenes. Nevertheless, it’s nonetheless 400 occasions quicker than our unique script.

Making Code Shorter and Extra Readable

In my earlier tutorial, we mentioned how one can use ChatGPT to study coding rapidly. In a single part, we requested ChatGPT to generate code that makes use of each lists and for loops. It gave us the next code in response:

1
numbers = [1, 2, 3, 4, 5]
2

3
# Compute the sq. of every quantity within the record utilizing a for loop
4
squared_numbers = []
5
for num in numbers:
6
    squared_numbers.append(num ** 2)
7

8
# Print the squared numbers
9
for squared_num in squared_numbers:
10
    print(squared_num)

Normally, there are a number of methods of writing a chunk of code to realize the identical performance. Typically, there are language-specific options that may make code that you’ve written shorter whereas sustaining or bettering readability.

For instance, the next immediate asks ChatGPT to make the given Python code shorter:

1
Can I make this Python code shorter whereas sustaining readability?

The response that I get again is:

1
numbers = [1, 2, 3, 4, 5]
2

3
# Compute the sq. of every quantity utilizing an inventory comprehension
4
squared_numbers = [num ** 2 for num in numbers]
5

6
# Print the squared numbers utilizing a for loop
7
for squared_num in squared_numbers:
8
    print(squared_num)

To illustrate you had written the identical code in JavaScript. It might look one thing like this:

1
let numbers = [1, 2, 3, 4, 5];
2

3
let squared_numbers = [];
4
for (let i = 0; i < numbers.size; i++) {
5
    squared_numbers.push(numbers[i] ** 2);
6
}
7

8
for (let i = 0; i < squared_numbers.size; i++) {
9
    console.log(squared_numbers[i]);
10
}

You could possibly ask ChatGPT to make use of ES6 to make your code shorter, whereas sustaining readability, through the use of the next immediate:

1
Make this JavaScript code shorter utilizing ES6 whereas sustaining readability.

In my case, the output was:

1
let numbers = [1, 2, 3, 4, 5];
2

3
let squared_numbers = numbers.map(num => num ** 2);
4

5
squared_numbers.forEach(num => console.log(num));

ChatGPT additionally supplies a proof, as you may see within the screenshot beneath:

Explanation of Shorter Readable Version by ChatGPTExplanation of Shorter Readable Version by ChatGPTExplanation of Shorter Readable Version by ChatGPT

Ultimate Ideas

On this tutorial, we discovered use ChatGPT to optimize code written in numerous languages. Optimization is not simply restricted to hurry and reminiscence utilization. You may also use ChatGPT to make your code extra readable, as we did within the final part.

My suggestion can be that you simply ask ChatGPT for insights to discover ways to do the identical factor utilizing a unique strategy. You may also explicitly ask ChatGPT to comply with greatest practices whereas optimizing your code.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments