Merge "Add PHPUnit test to ApiQueryDisabled"
[lhc/web/wiklou.git] / maintenance / benchmarks / benchmarkTidy.php
1 <?php
2
3 use MediaWiki\MediaWikiServices;
4
5 require __DIR__ . '/../Maintenance.php';
6
7 class BenchmarkTidy extends Maintenance {
8 public function __construct() {
9 parent::__construct();
10 $this->addOption( 'file', 'A filename which contains the input text', true, true );
11 $this->addOption( 'driver', 'The Tidy driver name, or false to use the configured instance',
12 false, true );
13 $this->addOption( 'tidy-config', 'JSON encoded value for the tidy configuration array',
14 false, true );
15 }
16
17 public function execute() {
18 $html = file_get_contents( $this->getOption( 'file' ) );
19 if ( $html === false ) {
20 $this->fatalError( "Unable to open input file" );
21 }
22 if ( $this->hasOption( 'driver' ) || $this->hasOption( 'tidy-config' ) ) {
23 $config = json_decode( $this->getOption( 'tidy-config', '{}' ), true );
24 if ( !is_array( $config ) ) {
25 $this->fatalError( "Invalid JSON tidy config" );
26 }
27 $config += [ 'driver' => $this->getOption( 'driver', 'RemexHtml' ) ];
28 $driver = MWTidy::factory( $config );
29 } else {
30 $driver = MWTidy::singleton();
31 if ( !$driver ) {
32 $this->fatalError( "Tidy disabled or not installed" );
33 }
34 }
35
36 $this->benchmark( $driver, $html );
37 }
38
39 private function benchmark( $driver, $html ) {
40 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
41 $times = [];
42 $innerCount = 10;
43 $outerCount = 10;
44 for ( $j = 1; $j <= $outerCount; $j++ ) {
45 $t = microtime( true );
46 for ( $i = 0; $i < $innerCount; $i++ ) {
47 $driver->tidy( $html );
48 print $contLang->formatSize( memory_get_usage( true ) ) . "\n";
49 }
50 $t = ( ( microtime( true ) - $t ) / $innerCount ) * 1000;
51 $times[] = $t;
52 print "Run $j: $t\n";
53 }
54 print "\n";
55
56 sort( $times, SORT_NUMERIC );
57 $n = $outerCount;
58 $min = $times[0];
59 $max = end( $times );
60 if ( $n % 2 ) {
61 $median = $times[ ( $n - 1 ) / 2 ];
62 } else {
63 $median = ( $times[$n / 2] + $times[$n / 2 - 1] ) / 2;
64 }
65 $mean = array_sum( $times ) / $n;
66
67 print "Minimum: $min ms\n";
68 print "Median: $median ms\n";
69 print "Mean: $mean ms\n";
70 print "Maximum: $max ms\n";
71 print "Memory usage: " . $contLang->formatSize( memory_get_usage( true ) ) . "\n";
72 print "Peak memory usage: " .
73 $contLang->formatSize( memory_get_peak_usage( true ) ) . "\n";
74 }
75 }
76
77 $maintClass = BenchmarkTidy::class;
78 require RUN_MAINTENANCE_IF_MAIN;