现在的位置: 首页 -> PHP学习 -> php date()和sql FROM_UNIXTIME() 的效率比较,哪个好

php date()和sql FROM_UNIXTIME() 的效率比较,哪个好

2013-11-13 22:34评论数 0 ⁄ 被浏览 8459 views+

在php中,将int型的时间戳转换为日期时间,有两种方法,一种是用我们熟悉的函数date("Y-m-d H:i",time())来转换;还有一种是在sql中用 FROM_UNIXTIME(add_time, "%Y-%m-%d %H:%m") 转换,平时用的不多,估计很多人都还不知道吧。


为了了解他们之间的效率和区别,我做了一个实例。先建了一张表,只添加了两个字段,一个是自增长的id,一个是int型的时间,添加两条数据后,再用自我复制语句 insert into t1 (add_time) select add_time from t1 将表迅速的复制到10万多条数据,用于测试。


程序很简单,就是比较在mysql中转换和在php中转换执行时间比较。


每块代码我执行了很多遍,我从中取出的一个比较适中的时间,现在从下图可以很明显的看出在数据库中用 FROM_UNIXTIME() 函数比 php 的 date() 函数要高效的多,不过我们不能忽略mysql数据库执行的开销。所以在不考虑数据库开销的情况下 FROM_UNIXTIME() 是快速的。





PHP源码参考:


<?php

header("Content-type:text/html;charset=utf-8");

//程序运行时间

$starttime = explode(' ',microtime());


/*········以下是代码区·········*/

$link = mysql_connect("localhost","root","root");

mysql_select_db("test");

mysql_query("set names utf8");

$sql = "select add_time from t1 limit 100000";

$res = mysql_query($sql,$link);

$num = mysql_num_rows($res);

while($row = mysql_fetch_array($res)){

//echo date("Y-m-d H:i",$row['add_time'])." | ";

}

/*········以上是代码区·········*/


//程序运行时间

$endtime = explode(' ',microtime());

$thistime = $endtime[0]+$endtime[1]-($starttime[0]+$starttime[1]);

$thistime = round($thistime,3);

echo '<hr/>本次通过 PHP 中 date("Y-m-d H:i",$row["add_time"]) 转换。<br/> 转换本次转换 '.$num.' 条数据。<br/>本次执行耗时:'.$thistime.' 秒。';


//--------------------------------------------------------

//--------------------------------------------------------

//程序运行时间

$starttime = explode(' ',microtime());


/*········以下是代码区·········*/

$sql = "select add_time from t1 limit 100000";

$res = mysql_query($sql,$link);

$num = mysql_num_rows($res);

while($row = mysql_fetch_array($res)){

echo $row['add_time']." | ";

}

/*········以上是代码区·········*/


//程序运行时间

$endtime = explode(' ',microtime());

$thistime = $endtime[0]+$endtime[1]-($starttime[0]+$starttime[1]);

$thistime = round($thistime,3);

echo '<hr/>本次直接输出,没任何转换<br/>本次执行耗时:'.$thistime.' 秒。';


//--------------------------------------------------------

//--------------------------------------------------------

//程序运行时间

$starttime = explode(' ',microtime());


/*········以下是代码区·········*/

$sql = "select FROM_UNIXTIME( add_time, '%Y-%m-%d %H:%m' ) as add_time from t1 limit 100000";

$res = mysql_query($sql,$link);

$num = mysql_num_rows($res);

while($row = mysql_fetch_array($res)){

//echo $row['add_time']." | ";

}

/*········以上是代码区·········*/


//程序运行时间

$endtime = explode(' ',microtime());

$thistime = $endtime[0]+$endtime[1]-($starttime[0]+$starttime[1]);

$thistime = round($thistime,3);

echo '<hr/>本次通过 mysql 中 FROM_UNIXTIME( add_time, "%Y-%m-%d %H:%m" ) 转换。<br/> 转换本次转换 '.$num.' 条数据。<br/>本次执行耗时:'.$thistime.' 秒。';


?>

 

文章出自:https://www.daixiaorui.com/read/58.html 本站所有文章,除注明出处外皆为原创,转载请注明本文地址,版权所有。

目前有 0 条评论  @我要评论

    您的每一个评论都是对我的一份支持

     博客二维码

    昵称 *

    邮箱 *