|
项目中有个组件是用perl语言编写,最近该组件有个新需求要开发,学习代码的过程中发现现有代码连数据库的方式是用sqlplus连接oracle,将其数据生成到文本文件,再利用读文件的方式读入到内存数据结构中. 这种方式虽然能解决问题,如果改成直连数据库,就可以不用文本文件中转了,性能是否也会提升?
让我们来对比下, 以下代码分成两块 if块里的内容是直连,else块里的内容是sqlplus方式.
数据量是60W条左右.
#!/usr/bin/perl
use DBI;
my $now1 = time;
if(0) {
$dbname="sid";
$user="user";
$passwd="password";
$dbh="";
$dbh = DBI->connect("dbi:Oracle:$dbname",$user,$passwd) or die "can't connect to
database ". DBI-errstr;
#连接数据库
$sth=$dbh->prepare("select * from dba_source");
$sth->execute;
#执行sql语句
while (@recs=$sth->fetchrow_array) {
#读取记录数据
print $recs[0].":".$recs[1].":".$recs[2]."\n";
}
#断开连接
$dbh->disconnect;
}
else {
system "sqlplus", "system/orcl\@ORCL", "\@zsql.sql";
my $dbdata = "C:/Perl/bin/test/dbout.txt";
open(IN, $dbdata);
while(<IN>) {
chomp;
my $oneLine = $_;
print "oneLine:$oneLine\n";
}
}
my $now2 = time;
my $diff = $now2 - $now1;
print "time cost:$diff s\n";
oracle直连:
第5行的条件改成1,运行3次,耗时分别为 58s, 58s, 50s.
sqlplus连接:
第5行的条件改成0,运行3次,耗时分别为 260s, 209s, 147s.
可见,虽然sqlplus连接第三次运行的耗时在不断减少,但不可否认,直连比sqlplus方式至少快1倍.
通过加上-d:NYTProf运行,并生成html后,
perl -d:NYTProf z1.pl
nytprofhtml nytprof.out
我们可以看到sqlplus语句的运行时间是27.3s,而直连时只消耗了375ms.
细心的读者可能会发现sqlplus连接时耗时从260->209->147,耗时减少明显,那到底是sql数据被缓存还是perl自身的优化呢? 通过对比两次sqlplus运行的prof信息,我们可以看到print语句运行时间从171s降低到了41s, 看来是perl内部对print做了些优化.
|
|
|