11import time
2+ from pathlib import Path
23
34import mujoco
45import numpy as np
56
67from mujoco_lidar import MjLidarWrapper , scan_gen
78
8-
9- def create_benchmark_scene ():
10- """创建基准测试场景"""
11- xml = """
12- <mujoco>
13- <worldbody>
14- <body name="box1" pos="2 0 0.5">
15- <geom type="box" size="0.5 0.5 0.5"/>
16- </body>
17- <body name="box2" pos="0 2 0.5">
18- <geom type="box" size="0.5 0.5 0.5"/>
19- </body>
20- <body name="sphere" pos="-2 0 0.5">
21- <geom type="sphere" size="0.5"/>
22- </body>
23- <site name="lidar_site" pos="0 0 1"/>
24- </worldbody>
25- </mujoco>
26- """
27- return mujoco .MjModel .from_xml_string (xml )
9+ _ROOT = Path (__file__ ).resolve ().parent .parent
10+ _MODELS_DIR = _ROOT / "models"
11+ _TRACE_SCENES = {
12+ "go2" : "scene_go2.xml" ,
13+ "go2_stairs" : "scene_go2_stairs_terrain.xml" ,
14+ }
2815
2916
3017def benchmark_ray_generation (n_runs = 10 ):
@@ -49,52 +36,121 @@ def benchmark_ray_generation(n_runs=10):
4936 "mean_ms" : np .mean (times ) * 1000 ,
5037 "std_ms" : np .std (times ) * 1000 ,
5138 "n_rays" : len (theta ),
39+ "m_rays_per_sec" : len (theta ) / np .mean (times ) / 1e6 ,
5240 }
5341
5442 return results
5543
5644
57- def benchmark_trace_rays (backend = "cpu" , n_runs = 10 ):
45+ def load_model (filename ):
46+ return mujoco .MjModel .from_xml_path ((_MODELS_DIR / filename ).as_posix ())
47+
48+
49+ def benchmark_trace_rays (scene_name , scene_file , backend = "cpu" , n_runs = 10 ):
5850 """基准测试:射线追踪速度"""
59- model = create_benchmark_scene ( )
51+ model = load_model ( scene_file )
6052 data = mujoco .MjData (model )
53+ mujoco .mj_resetDataKeyframe (model , data , 0 )
54+ mujoco .mj_forward (model , data )
55+
56+ geomgroup = np .ones ((mujoco .mjNGROUP ,), dtype = np .ubyte )
57+ geomgroup [3 :] = 0
6158
6259 try :
63- lidar = MjLidarWrapper (model , site_name = "lidar_site" , backend = backend )
60+ lidar = MjLidarWrapper (
61+ model ,
62+ site_name = "lidar" ,
63+ backend = backend ,
64+ args = {"bodyexclude" : model .body ("base" ).id , "geomgroup" : geomgroup },
65+ )
6466 except ImportError :
6567 return None
6668
67- theta , phi = scan_gen .generate_HDL64 ()
69+ theta , phi = scan_gen .LivoxGenerator ("mid360" ).sample_ray_angles ()
70+ theta = np .ascontiguousarray (theta ).astype (np .float32 )
71+ phi = np .ascontiguousarray (phi ).astype (np .float32 )
6872
6973 # Warmup
70- lidar .trace_rays (data , theta , phi )
74+ ranges = lidar .trace_rays (data , theta , phi )
75+ if hasattr (ranges , "block_until_ready" ):
76+ ranges .block_until_ready ()
7177
7278 times = []
7379 for _ in range (n_runs ):
7480 start = time .perf_counter ()
75- lidar .trace_rays (data , theta , phi )
81+ ranges = lidar .trace_rays (data , theta , phi )
82+ if hasattr (ranges , "block_until_ready" ):
83+ ranges .block_until_ready ()
7684 elapsed = time .perf_counter () - start
7785 times .append (elapsed )
7886
7987 return {
88+ "scene" : scene_name ,
8089 "backend" : backend ,
8190 "mean_ms" : np .mean (times ) * 1000 ,
8291 "std_ms" : np .std (times ) * 1000 ,
8392 "n_rays" : len (theta ),
84- "rays_per_sec " : len (theta ) / np .mean (times ),
93+ "m_rays_per_sec " : len (theta ) / np .mean (times ) / 1e6 ,
8594 }
8695
8796
97+ def print_table (headers , rows ):
98+ widths = [len (header ) for header in headers ]
99+ for row in rows :
100+ for i , value in enumerate (row ):
101+ widths [i ] = max (widths [i ], len (value ))
102+
103+ fmt = " " .join (f"{{:<{ width } }}" for width in widths )
104+ print (fmt .format (* headers ))
105+ print (fmt .format (* ["-" * width for width in widths ]))
106+ for row in rows :
107+ print (fmt .format (* row ))
108+
109+
88110if __name__ == "__main__" :
111+ generation_rows = []
112+ tracing_rows = []
113+
89114 print ("=== Ray Generation Benchmark ===" )
90115 gen_results = benchmark_ray_generation ()
91116 for name , result in gen_results .items ():
92- print (f"{ name } : { result ['mean_ms' ]:.2f} ±{ result ['std_ms' ]:.2f} ms ({ result ['n_rays' ]} rays)" )
117+ print (
118+ f"{ name } : { result ['mean_ms' ]:.2f} ±{ result ['std_ms' ]:.2f} ms "
119+ f"({ result ['m_rays_per_sec' ]:.3f} M rays/s)"
120+ )
121+ generation_rows .append (
122+ [
123+ name ,
124+ str (result ["n_rays" ]),
125+ f"{ result ['mean_ms' ]:.2f} " ,
126+ f"{ result ['std_ms' ]:.2f} " ,
127+ f"{ result ['m_rays_per_sec' ]:.3f} M rays/s" ,
128+ ]
129+ )
93130
94131 print ("\n === Ray Tracing Benchmark ===" )
95- for backend in ["cpu" , "taichi" , "jax" , "warp" ]:
96- result = benchmark_trace_rays (backend )
97- if result :
98- print (
99- f"{ backend } : { result ['mean_ms' ]:.2f} ±{ result ['std_ms' ]:.2f} ms ({ result ['rays_per_sec' ]:.0f} rays/s)"
100- )
132+ for scene_name , scene_file in _TRACE_SCENES .items ():
133+ print (f"\n --- { scene_name } ({ scene_file } ) ---" )
134+ for backend in ["cpu" , "taichi" , "jax" , "warp" ]:
135+ result = benchmark_trace_rays (scene_name , scene_file , backend )
136+ if result :
137+ print (
138+ f"{ backend } : { result ['mean_ms' ]:.2f} ±{ result ['std_ms' ]:.2f} ms "
139+ f"({ result ['m_rays_per_sec' ]:.3f} M rays/s)"
140+ )
141+ tracing_rows .append (
142+ [
143+ scene_name ,
144+ backend ,
145+ str (result ["n_rays" ]),
146+ f"{ result ['mean_ms' ]:.2f} " ,
147+ f"{ result ['std_ms' ]:.2f} " ,
148+ f"{ result ['m_rays_per_sec' ]:.3f} M rays/s" ,
149+ ]
150+ )
151+
152+ print ("\n === Ray Generation Summary ===" )
153+ print_table (["Name" , "Rays" , "Mean ms" , "Std ms" , "Throughput" ], generation_rows )
154+
155+ print ("\n === Ray Tracing Summary ===" )
156+ print_table (["Scene" , "Backend" , "Rays" , "Mean ms" , "Std ms" , "Throughput" ], tracing_rows )
0 commit comments