0

I have the below block of code,

***Scenario 1:***
def sample_function():
    input = {'gw_mac': ['ac1403', 'ac15cf', 'ac15cf'], 'mac': ['820', '94c', '94c']}
    df = pd.DataFrame(data=input)
    unique_mac_list = [index for index, group in df.groupby(['gw_mac', 'mac'])]

    print("unique_mac_list :: ", str(unique_mac_list))

if __name__ == '__main__':
    print(timeit.timeit("sample_function()", setup="from __main__ import sample_function", number=10))




***Scenario 2:***

def sample_function():
    input = {'gw_mac': ['ac1403', 'ac15cf', 'ac15cf'], 'mac': ['820', '94c', '94c']}
    df = pd.DataFrame(data=input)
    unique_mac_list = []
    for index, group in df.groupby(['gw_mac', 'mac']):
        unique_mac_list.append(index)

    print("unique_mac_list :: ", str(unique_mac_list))

if __name__ == '__main__':
    print(timeit.timeit("sample_function()", setup="from __main__ import sample_function", number=10))

The time taken to execute the above mentioned two scenarios are,

***Scenario 1:-***
0.018882042000768706

***Scenario 2:-***
0.01927675799925055

Provided both the scenario contains the same data in "bleStreamData_df". In what ways, list comprehension is efficient then looping?

Mahamutha M
  • 1,235
  • 1
  • 8
  • 24
  • 1
    You should use `%timeit` to measure running time, not `time.time()`. The measurements that you present are random and subject to a lot of factors, such as system load. – DYZ Mar 20 '19 at 04:36
  • 1
    Please also include [`timeit`](https://docs.python.org/3/library/timeit.html) results. – awesoon Mar 20 '19 at 04:36
  • 1
    Possible duplicate of [Are list-comprehensions and functional functions faster than "for loops"?](https://stackoverflow.com/questions/22108488/are-list-comprehensions-and-functional-functions-faster-than-for-loops) – anky Mar 20 '19 at 04:36
  • @awesoon, I have included the %timeit. I want to know, How scenario 2 takes less time compared to scenario 1 for the same dataset? – Mahamutha M Mar 20 '19 at 06:08
  • 1
    You are measuring a list creation instead of measuring the algo. Please read again examples in the [`timeit`](https://docs.python.org/3/library/timeit.html) link. – awesoon Mar 20 '19 at 06:21
  • 1
    And make sure to run these measurements independently – awesoon Mar 20 '19 at 06:22
  • @awesoon, Thank You. I have found my issue. – Mahamutha M Mar 20 '19 at 07:13

0 Answers0