本帖最後由 hknovo 於 2013-7-15 14:43 編輯 . @. |& f$ l7 o4 O0 R7 L* n0 B( ?9 q, X
. B7 S8 ^9 F% I6 x- F$ \* }網站訪問速度,也是影響GOOGLE 排名的一種因素之一。GOOGLE 還提供了 page speed 來檢測代碼。 混世魔王的英文站研究,一般都是用WP的程序。 但是,WP畢竟是BLOG,數據庫達到幾萬片文章後,就特別慢。 有的時候,為了頁面多被GOOGLE 收錄。就採用用隨機參數。 混世魔王英文站研究 之 優化wordpress mysql 的執行效率。 例如,這一段分類隨機的代碼。在只有幾百篇的文章下是執行正常的。 - <?php
- $rand_posts = get_posts("cat=" . the_category_ID(0) . "&orderby=rand&showposts=10");
- foreach( $rand_posts as $post ) :
- ?>
- <li><h3><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></h3></li>
- <?php endforeach; ?>
- . _* U# w- ~% {1 y+ M
/ H0 H* \1 @* G5 V+ E+ P[color=rgb(51, 102, 153) !important]複製代碼
4 U2 U* \. S, }4 Y# [在幾萬片文章下,服務器直接 time out
6 f: z* N+ I2 O; b- i+ n
) A2 V; g' r' O+ M/ D% u因為之前的隨機是在幾萬篇文章中隨機的, 我們加入一個隨機值,看看下面的代碼。 - <font face="Tahoma, Verdana,">
<?php$t1=microtime(true);$rd=mt_rand(0,1000);$myposts=get_posts('numberposts=100&offset='.$rd.'&category='.the_category_ID(0));foreach($myposts as $post) :echo microtime(true)-$t1."";setup_postdata($post);?> <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li><?php endforeach; ?> </font>
9 O1 _. f/ l' d# _: ?+ W! o$ G4 R. ^8 a, X0 p) ?* i
[color=rgb(51, 102, 153) !important]複製代碼' I$ q5 j7 I# x9 M. A2 d. i
網站能顯示了。但是 MYSQL 的數據庫查詢值在 8 秒
/ \5 a! T; r( \; ~
% w- d. ]/ t/ m" U, n; ~' f5 D p繼續,優化。 - <font face="Tahoma, Verdana,">
<?php$t1=microtime(true);$rand_posts = $wpdb->get_results("SELECT id,post_title FROM $wpdb->posts WHERE id >= (SELECT floor(RAND() * (SELECT MAX(id) FROM $wpdb->posts))) ORDER BY id LIMIT 0,200");echo microtime(true)-$t1."";foreach($rand_posts as $post ){?><li><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></li><?php } ?> </font>2 Y- P7 \; f* b- G
2 G2 _- h1 f( ?
7 _3 b) t; e' W. C- Q4 ~複製代碼
; S- N! p5 z4 C* D+ \' l8 B! t 可以看到,上萬的文章,隨機輸出200篇,查詢 0.02 秒。 執行效率得到大幅度提升。 - <?php. P$ W# ?) O, l; b( d) v
- $t1=microtime(true);
" B+ S! S* B& y3 ?7 ]5 p/ B - $wpcount = $wpdb->get_var($wpdb->prepare("SELECT count(*) FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish'"));
/ m+ z* [; K4 @- W. c" T - 9 c0 M+ R8 Z8 L7 e, a# @
- $randid = mt_rand(0,$wpcount-12);
* J' K" e8 x! _& K, p+ \3 ~4 {) y/ f - $myposts = $wpdb->get_results("SELECT id,post_title FROM $wpdb->posts WHERE post_type = 'post' AND post_status ='publish' and id>$randid limit 12");5 |7 A) g/ \& ^# C( p6 l
- echo microtime(true)-$t1."
& a% l, x7 G7 f, |! f: N! P - ";
# n5 ], B# e. H; ^ - foreach($myposts as $post){
$ V' g( `# B/ p/ P - ?>: p8 s. I) D* g
- <li><a href="<?php echo get_permalink($post->id); ?>" title="<?php echo $post->post_title; ?>"><?php echo $post->post_title; ?></a></li>
& g. E1 d1 t/ ~! m8 n# o: c9 D& g0 B - <?php
9 Q7 U- a1 r) `, t/ n7 q - }?>
複製代碼麻煩上面扣分的,把我的豬毛還來,賺兩幣容易嗎? 不加就算了,還給我減了
* H/ c4 {" q: I( z! r' ^4 c: H# Y" }; }! q+ e! X" u
|