Created
September 10, 2020 11:47
-
-
Save priteshgohil/ea3fd8fc89f0112d09fe8cd77de79067 to your computer and use it in GitHub Desktop.
Performance on calculating mean
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
import statistics | |
import numpy as np | |
def mean_normal(list_data): | |
""" | |
Calculate mean of python list normaly | |
input: list of int or float | |
output: mean value | |
""" | |
start = time.time() | |
avg = sum(list_data)/len(list_data) | |
end = time.time() | |
print("avg: {} & Time taken by mean_normal: {:.5f} sec".format(avg, end-start)) | |
return avg | |
def mean_statistics(list_data): | |
""" | |
Calculate mean of python list using statistics lib | |
input: list of int or float | |
output: mean value | |
""" | |
start = time.time() | |
avg = statistics.mean(list_data) | |
end = time.time() | |
print("avg: {} & Time taken by mean_statistics: {:.5f} sec".format(avg, end-start)) | |
return avg | |
def mean_numpy_with_list(list_data): | |
""" | |
Calculate mean of python list using numpy lib | |
input: list of int or float | |
output: mean value | |
""" | |
start = time.time() | |
avg = np.mean(list_data) | |
end = time.time() | |
print("avg: {} & Time taken by mean_numpy_with_list: {:.5f} sec".format(avg, end-start)) | |
return avg | |
def mean_numpy_with_array(array_data): | |
""" | |
Calculate mean of numpy array using numpy lib | |
input: 1-d numpy array | |
output: mean value | |
""" | |
start = time.time() | |
avg = np.mean(array_data) | |
end = time.time() | |
print("avg: {} & Time taken by mean_numpy_with_array: {:.5f} sec".format(avg, end-start)) | |
return avg | |
if __name__ == '__main__': | |
# Test with int range | |
data = list(range(3000000)) | |
mean_normal(data) | |
mean_statistics(data) | |
mean_numpy_with_list(data) | |
mean_numpy_with_array(np.array(data)) | |
# Test with float range | |
data = list(np.linspace(500,1000,3000000)) | |
mean_normal(data) | |
mean_statistics(data) | |
mean_numpy_with_list(data) | |
mean_numpy_with_array(np.array(data)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For my system, the following are results,
To Do:
[ ] Add graph of time vs length of the list.