<script src='https://cdn.jsdelivr.net/pyodide/v0.26.3/full/pyodide.js'></script>
async function globalMeasureThatScriptPrepareFunction() {
window.globalPyodide = await loadPyodide();
console.log(globalPyodide.runPython('import sys; sys.version'));
await globalPyodide.loadPackage('numpy');
await globalPyodide.runPython(`
import numpy as np
import random
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
def efficient_sort(arr):
return sorted(arr)
def generate_random_array(size, lower_bound, upper_bound):
return [random.randint(lower_bound, upper_bound) for _ in range(size)]
# Generate a random array
random_array = generate_random_array(250, 1, 500000)
print("Original array:", random_array)
`);
}
window.globalPyodide.runPython(`
bubble_sort(random_array.copy())
`);
window.globalPyodide.runPython(`
efficient_sort(random_array.copy())
`);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Test #1 bubble_sorted_array | |
Test#2 efficient_sorted_array |
Test name | Executions per second |
---|---|
Test #1 bubble_sorted_array | 148.3 Ops/sec |
Test#2 efficient_sorted_array | 1150.1 Ops/sec |
The provided benchmark tests the performance of two sorting algorithms in Python, executed within a JavaScript environment using the Pyodide library. Pyodide is a tool that allows Python code to run in the browser using WebAssembly, which bridges the gap between JavaScript and Python environments.
The benchmark compares two sorting methods:
Bubble Sort (bubble_sort
)
bubble_sort(random_array.copy())
Efficient Sort (efficient_sort
)
sorted
function, which is optimized and typically implemented using Timsort, a hybrid sorting algorithm derived from merge sort and insertion sort.efficient_sort(random_array.copy())
Pros:
Cons:
Pros:
Cons:
Other sorting algorithms that could be considered for benchmarking purposes include:
Each of these alternatives offers distinct advantages and might be more suitable for specific applications or datasets depending on size, structure, and the required characteristics of the sort (stability, memory usage, etc.), demonstrating the importance of choosing the right algorithm for the task at hand.