How to efficiently count the number of images in each class in a dataset?

I have been using this code to count the number of images in each class for my dataset, but it’s extremely slow. Is there a better more efficient way to get the number of images in each class?

def count_classes(dataset):
    class_counts = dict(Counter(sample_tup[1] for sample_tup in dataset))
    return dict(sorted(class_counts.items()))