Skip to content

Commit 93fd0c0

Browse files
authored
Merge pull request #390 from cleophass/AvoidSqrtInLoop
GCI106 AvoidSqrtInLoop #Python #DLG #RulesSpecifications
2 parents 77db3a4 + 6c5ec6a commit 93fd0c0

File tree

5 files changed

+72
-0
lines changed

5 files changed

+72
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
99

1010
### Added
1111

12+
- [#390](https://github.com/green-code-initiative/creedengo-rules-specifications/pull/390) Added rule GCI106 : Detect scalar sqrt usage in loops and suggest vectorized alternatives
1213
- [#389](https://github.com/green-code-initiative/creedengo-rules-specifications/pull/389) Add rule GCI105, Add a rule on Python String Concatenation
1314
- [#388](https://github.com/green-code-initiative/creedengo-rules-specifications/pull/388) Added rule GCI104 on Torch Tensor types
1415
- [#387](https://github.com/green-code-initiative/creedengo-rules-specifications/pull/387) Add rule GCI103, add specifications for a new rule on iteration method for dict in Python

RULES.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ Some are applicable for different technologies.
8282
| GCI103 | Don't use .items() to iterate over a dictionary when only keys or values are needed | Avoid using `.items()` if you only use the key or the value, as this creates an unnecessary tuple, leading to increased memory allocation and slower execution. | |||| 🚀 ||||
8383
| GCI104 | DATA/AI PyTorch - Create tensors directly from Torch | In PyTorch, prefer creating tensors directly using `torch.rand`, `torch.tensor`, or other Torch methods instead of converting from NumPy arrays. Avoid using `torch.tensor(np.random.rand(...))` or similar patterns when the same result can be achieved directly with PyTorch. | | 🚫 | 🚫 | 🚫 | 🚀 | 🚫 | 🚫 | 🚫 |
8484
| GCI105 | Python String Concatenation | Python String Concatenation - Use Join Instead or f-Strings instead of += | | 🚫 | 🚫 | 🚫 | 🚀 | 🚫 | 🚫 | 🚫 |
85+
| GCI106 | Avoid Square Root Operations In Loop | Using scalar `math.sqrt` (or `numpy.sqrt` on individual values) inside loops leads to inefficient code | | 🚫 | 🚫 | 🚫 | 🚀 | 🚫 | 🚫 | 🚫 |
8586
| GCI203 | Detect unoptimized file formats | When it is possible, to use svg format image over other image format | | 🚧 | 🚀 | 🚀 || 🚀 | 🚀 | 🚫 |
8687
| GCI404 | Avoid list comprehension in iterations | Use generator comprehension instead of list comprehension in for loop declaration | | 🚫 | 🚫 | 🚫 || 🚫 | 🚫 | 🚫 |
8788
| GCI522 | Sobriety: Brightness Override | To avoid draining the battery, iOS and Android devices adapt the brightness of the screen depending on the environment light. | | 🚫 | 🚫 || 🚫 | 🚫 | 🚫 | 🚫 |

src/main/rules/GCI106/GCI106.json

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
{
2+
"title": "Numpy Data - Avoid Square Root Operations In Loop",
3+
"type": "CODE_SMELL",
4+
"status": "ready",
5+
"remediation": {
6+
"func": "Constant\/Issue",
7+
"constantCost": "5min"
8+
},
9+
"tags": [
10+
"creedengo",
11+
"eco-design",
12+
"performance",
13+
"data",
14+
"numpy"
15+
],
16+
"defaultSeverity": "Minor"
17+
}
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
Using scalar `math.sqrt` (or `numpy.sqrt` on individual values) inside loops leads to inefficient code due to repeated function calls and missed opportunities for vectorization. Prefer using vectorized square root operations on entire arrays to improve performance and reduce environmental impact.
2+
3+
== Non Compliant Code Example
4+
5+
[source,python]
6+
----
7+
import math
8+
data = [1, 4, 9, 16]
9+
results = []
10+
11+
for value in data:
12+
results.append(math.sqrt(value)) # Noncompliant: scalar sqrt in a loop
13+
----
14+
15+
== Compliant Solution
16+
17+
[source,python]
18+
----
19+
import numpy as np
20+
data = np.array([1, 4, 9, 16])
21+
results = np.sqrt(data) # Compliant: vectorized sqrt
22+
----
23+
24+
25+
== Relevance Analysis
26+
27+
This rule is relevant to scientific computing, data analysis, and machine learning workloads where element-wise mathematical operations are common and often occur within loops. Replacing scalar calls with vectorized array operations improves code efficiency and environmental impact.
28+
29+
=== Configuration
30+
31+
* Processor: Intel(R) Core(TM) Ultra 5 135U, 2100 MHz, 12 cores, 14 logical processors
32+
* RAM: 16 GB
33+
* CO2 Emissions Measurement: Using https://mlco2.github.io/codecarbon/[CodeCarbon]
34+
35+
=== Context
36+
37+
Two approaches were benchmarked:
38+
- *Non-compliant:* Using `math.sqrt()` inside a loop over Python lists
39+
- *Compliant:* Using `numpy.sqrt()` on an entire NumPy array
40+
41+
=== Impact Analysis
42+
43+
image::results.png[]
44+
45+
== Conclusion
46+
47+
Replacing scalar `sqrt` operations inside loops with vectorized NumPy operations: Significantly reduces carbon footprint
48+
49+
It's important to keep in mind that this is true for a vectorized operation. When wanting to square root a single value, the `math.sqrt` function is the best option. The `numpy.sqrt` function is not optimized for single values and will be slower than the `math.sqrt` function.
50+
51+
== References
52+
53+
- https://numpy.org/doc/stable/reference/generated/numpy.sqrt.html
21.7 KB
Loading

0 commit comments

Comments
 (0)