green-code-initiative / ecoCode-challenge

Emboard in the hackhatons serie for improving ecoCode
3 stars 4 forks source link

[Hackaton 2024][Coach Team][Python] Copying a list using `list.append(x)` within a loop is not energy efficient. (Rule example for Hackaton spotter - measure justification) #92

Open jhertout opened 4 months ago

jhertout commented 4 months ago

Rule title

Using list.append(x) within a loop is not energy efficient.

Language and platform

Python.

Rule description

Using list.append(x) within a loop to copy a list is not energy efficient. Prefer the usage of native methods which are more energy friendly.

Noncompliant Code Example

    list = [1, 2, 3, 4, 5]
    new_list = []
    for item in list:
        new_list.append(item)

Compliant Solution

    list = [1, 2, 3, 4, 5]
    new_list = []
    new_list = list.copy()

Rule short description

Using list.append(x) within a loop is not energy efficient.

Rule justification

Here are some measures performed using RAPL on a computer with a CPU Intel(R) Xeon(R) CPU E3-1245 v5 @ 3.50GHz. This computer was running only the tests but to limit the impact of perturbation on the results, the tests were performed several time.

Tested code (non compliant)

list = ['1', '2']
for i in range(5000000):
   new_list = []
   for item in list:
       new_list.append(item)

Tested code (compliant)

list = ['1', '2']
for i in range(5000000):
    list.copy()

We perform the copy of a list using two different methods (append or list.copy) and we perform the copy 5000000 time. The test was done 5 time for each function and there is the result:

append in loop

Number of iteration Consumption (Joules)
1 1723.98
2 1813.46
3 1885.35
4 1800.87
5 1744.04

list.copy

Number of iteration Consumption (Joules)
1 626.35
2 616.29
3 620.61
4 621.93
5 615.08

Conclusion: as we can see using list.copy() is more energy efficient in this simple case. More tests should be done using a bigger list or other type of list but we clearly have the tendency for the rule definition.

Severity / Remediation Cost

Estimate the severity and remediation cost of your issue.

Implementation principle

dedece35 commented 4 months ago

my first review ok