@@ -953,3 +953,66 @@ func TestDisplayablePorts(t *testing.T) {
953953 assert .Check (t , is .Equal (port .expected , actual ))
954954 }
955955}
956+
957+ // genContainers generates a list of containers to be used as a realistic
958+ // input for benchmarks; the containers have all fields set that are used
959+ // by the various formats.
960+ func genContainers (count int ) []container.Summary {
961+ created := time .Now ().Add (- 72 * time .Hour ).Unix ()
962+ containers := make ([]container.Summary , 0 , count )
963+ for i := range count {
964+ containers = append (containers , container.Summary {
965+ ID : fmt .Sprintf ("%064x" , i ),
966+ Names : []string {fmt .Sprintf ("/container_%d" , i ), fmt .Sprintf ("/other_name_%d" , i )},
967+ Image : "docker.io/library/ubuntu:24.04" ,
968+ ImageID : fmt .Sprintf ("sha256:%064x" , i ),
969+ Command : `/bin/sh -c "while true; do echo hello world; sleep 1; done"` ,
970+ Created : created ,
971+ Ports : []container.PortSummary {
972+ {IP : netip .MustParseAddr ("0.0.0.0" ), PrivatePort : 80 , PublicPort : uint16 (30000 + i ), Type : "tcp" },
973+ {IP : netip .MustParseAddr ("::" ), PrivatePort : 443 , PublicPort : uint16 (40000 + i ), Type : "tcp" },
974+ {PrivatePort : 8080 , Type : "tcp" },
975+ },
976+ SizeRw : 123456789 ,
977+ SizeRootFs : 987654321 ,
978+ Labels : map [string ]string {
979+ "com.docker.compose.project" : "some-project" ,
980+ "com.docker.compose.service" : fmt .Sprintf ("service-%d" , i ),
981+ "org.opencontainers.image.source" : "https://github.com/docker/cli" ,
982+ },
983+ State : "running" ,
984+ Status : "Up 3 days (healthy)" ,
985+ Mounts : []container.MountPoint {
986+ {Type : "volume" , Name : fmt .Sprintf ("volume-%d" , i ), Destination : "/data" },
987+ {Type : "bind" , Source : "/tmp/source" , Destination : "/mnt/source" },
988+ },
989+ })
990+ }
991+ return containers
992+ }
993+
994+ func BenchmarkContainerWrite (b * testing.B ) {
995+ containers := genContainers (100 )
996+ for _ , tc := range []struct {
997+ doc string
998+ format Format
999+ }{
1000+ {doc : "table" , format : NewContainerFormat ("table" , false , false )},
1001+ {doc : "table-with-size" , format : NewContainerFormat ("table" , false , true )},
1002+ {doc : "quiet" , format : NewContainerFormat ("table" , true , false )},
1003+ {doc : "raw" , format : NewContainerFormat ("raw" , false , false )},
1004+ {doc : "json" , format : NewContainerFormat ("json" , false , false )},
1005+ {doc : "custom" , format : NewContainerFormat (`{{.ID}}: {{.Names}} {{.Ports}} {{.Labels}} {{.Mounts}}` , false , false )},
1006+ } {
1007+ b .Run (tc .doc , func (b * testing.B ) {
1008+ b .ReportAllocs ()
1009+ out := bytes .NewBuffer (nil )
1010+ for b .Loop () {
1011+ out .Reset ()
1012+ if err := ContainerWrite (Context {Format : tc .format , Output : out , Trunc : true }, containers ); err != nil {
1013+ b .Fatal (err )
1014+ }
1015+ }
1016+ })
1017+ }
1018+ }
0 commit comments