`
qiezi
  • 浏览: 495825 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

C++/D/Python性能比较续

阅读更多
周末抽空做了点小测试,根据http://blog.vckbase.com/jzhang/archive/2006/03/28/18807.html中m网友修改的算法,python版本中读取所有行以后就做一个排序,再去除重复项。这个算法在我的机器上执行时间是1735ms左右,属于python版本中最快的一个。

D版本暂还没想到有更优化的做法,D在处理以char[]作key的关联数组时,判断方法是先判断hash,如果hash相等,则继续做字符串判断。它执行时间是1120ms左右。

以D版本为基础,自己写了一个C++的Email类:

<!---->class Email
{
private:
        
string mail;
        size_t hash;
        friend 
bool operator < (const Email& lhs, const Email& rhs);
public:
        Email (
const char* mail_)
                : mail(mail_), hash(my_hash(mail_))
        {
        }
};

bool operator < (const Email& lhs, const Email& rhs)
{
        
if (lhs.hash == rhs.hash)
                
return lhs.mail < rhs.mail;
        
return lhs.hash < rhs.hash;
}

把它插入set并判断是否有重复。

这个程序由于string的大量拷贝,以及大量内存分配,执行时间相当长,在我的机器上是5s左右。D和python版本由于对象拷贝成本较低,加上都有内存分配策略,自然有一些优势。

退而求其次,既然hash冲突的几率较低,试试只保存hash:

<!---->class Email
{
private:
        size_t hash;
        friend 
bool operator < (const Email& lhs, const Email& rhs);
public:
        Email (
const char* mail_)
                : hash(my_hash(mail_))
        {
        }
};

bool operator < (const Email& lhs, const Email& rhs)
{
        
return lhs.hash < rhs.hash;
}

这次测试就比较快了,耗时仅1020ms左右,比D版本还要快,当然它不是完善的版本。

考虑到构造成本,于是改为只用一个set<int>来保存hash值再测试,这次耗时是930ms。

实际上可以做一个改进的C++版本,一次性读入文件的全部内容到一个大缓冲区,把所有的\n字符修改为\0,用一个动态数组保存缓冲区的所有字符串指针,hash值也须计算并保存到数组。再用D的索引方式,先hash比较,再字符串比较,效率应该也不低。

实现了一个:
<!---->#include <iostream>
#include 
<string>
#include 
<set>
#include 
<fstream>
#include 
<iterator>
#include 
<sys/time.h>
using namespace std;


size_t my_hash (
const char* str)
{
        size_t ret 
= 0;
        
while (*str)
                ret 
= 11 * ret + *str++;
        
return ret;
}

class Email
{
private:
        size_t hash;
        
const char* mail;
        friend 
bool operator < (const Email& lhs, const Email& rhs);
public:
        Email (
const char* mail_)
                : hash(my_hash(mail_)), mail(mail_)
        {
        }
};

bool operator < (const Email& lhs, const Email& rhs)
{
        
if (lhs.hash == rhs.hash)
                
return strcmp(lhs.mail, rhs.mail) < 0;
        
return lhs.hash < rhs.hash;
}

int main(int argc, char** argv)
{
        
if (argc < 3)
        {
                cout 
<< "Wrong arguments" << endl;
                
return 1;
        }

        FILE
* fin = fopen(argv[1], "r");
        
if (!fin)
        {
                cout 
<< "Invalid input file" << endl;
                
return 2;
        }
        FILE
* fout = fopen(argv[2], "w");
        
if (!fout)
        {
                fclose(fin);
                cout 
<< "Invalid output file" << endl;
                
return 3;
        }

        timeval start, end;

        
const int BUF_SIZE = 20 * 1024 * 1024;
        
char* buffer = new char[BUF_SIZE];
        memset(buffer, 
0, BUF_SIZE);

        gettimeofday(
&start, 0);
        
set<Email> emails;

        size_t read 
= fread (buffer, BUF_SIZE, 1, fin);
        
char* begin = buffer;
        
char* current = buffer;

        
while (*current != '\0')
        {
                
if (*current == '\n')
                {
                        
*current = '\0';
                        
if (emails.insert(begin).second){
                                fputs(begin, fout);
                                fwrite(
"\n"11, fout);
                        }
                        begin 
= current + 1;
                }
                
++ current;
        }

        fclose(fout);
        fclose(fin);

        gettimeofday(&end, 0);

        printf(
"Time used: %d ms\n", ((end.tv_sec - start.tv_sec) * 1000 + (end.tv_usec - start.tv_usec) / 1000));

        delete[] buffer;
        
return 0;
}

memset不是必须的,不过我不知道如何获取读入的大小。fread读取后,如果读到EOF,则返回值为0。所以我这里用memset先初始化内存,但不把它计入耗时。new操作也没计入,因为其它语言比如python、D在启动时都由运行时做了类似工作。

这个程序在我的机器上耗时为1350ms左右。我想可慢在set上,对象拷贝?内存分配?

做了几个优化版本,没多大提高。


重新测试了下:
A、python(m网友版本):
lijie t # python test.py
1689.0411377
lijie t # python test.py
1711.40599251
lijie t # python test.py
1699.63312149
lijie t # python test.py
1712.00013161
lijie t # python test.py
1713.8838768

B、D版本:
lijie t # ./testd email.txt email-new.txt
1091
lijie t # ./testd email.txt email-new.txt
1070
lijie t # ./testd email.txt email-new.txt
1062
lijie t # ./testd email.txt email-new.txt
1062
lijie t # ./testd email.txt email-new.txt
1096

C、C++只比较hash,set<Email>版本:
lijie t # ./test3 email.txt email-new.txt
Time used: 981 ms
lijie t # ./test3 email.txt email-new.txt
Time used: 1000 ms
lijie t # ./test3 email.txt email-new.txt
Time used: 980 ms
lijie t # ./test3 email.txt email-new.txt
Time used: 986 ms
lijie t # ./test3 email.txt email-new.txt
Time used: 987 ms

D、C++只比较hash,set<int>版本:
lijie t # ./test4 email.txt email-new.txt
Time used: 951 ms
lijie t # ./test4 email.txt email-new.txt
Time used: 953 ms
lijie t # ./test4 email.txt email-new.txt
Time used: 947 ms
lijie t # ./test4 email.txt email-new.txt
Time used: 950 ms
lijie t # ./test4 email.txt email-new.txt
Time used: 962 ms

E、C++大缓冲区,比较hash和字符串,set<Email>版本:
lijie t # ./test5 email.txt email-new.txt
Time used: 1375 ms
lijie t # ./test5 email.txt email-new.txt
Time used: 1359 ms
lijie t # ./test5 email.txt email-new.txt
Time used: 1369 ms
lijie t # ./test5 email.txt email-new.txt
Time used: 1378 ms
lijie t # ./test5 email.txt email-new.txt
Time used: 1396 ms

F、C++大缓冲区,比较字符串版本:
lijie t # ./test6 email.txt email-new.txt
Time used: 1168 ms
lijie t # ./test6 email.txt email-new.txt
Time used: 1169 ms
lijie t # ./test6 email.txt email-new.txt
Time used: 1171 ms
lijie t # ./test6 email.txt email-new.txt
Time used: 1179 ms
lijie t # ./test6 email.txt email-new.txt
Time used: 1169 ms

从C、E和F来看,对象拷贝成本是比较高的,E版本仅仅比C版本多了个const char*成员变量,hash值比较散,很少会真的执行到strcmp。保持E版本对象结构不变,把operator <里面的实现改为C版本,测试结果如下:
lijie t # ./test5 email.txt email-new.txt
Time used: 1355 ms
lijie t # ./test5 email.txt email-new.txt
Time used: 1360 ms
lijie t # ./test5 email.txt email-new.txt
Time used: 1348 ms
lijie t # ./test5 email.txt email-new.txt
Time used: 1353 ms
lijie t # ./test5 email.txt email-new.txt
Time used: 1379 ms

效率只提高了一点点,这个版本仅仅比C版本多了个成员变量拷贝,竟然慢了这么多。说明Email对象的2个成员变量拷贝成本的确很高。

F版本相比之下反而效率很不错,主要原因是email数据不够复杂,仅通过前几位就可以比较出结果。如果每行数据比较长,而且很多行要到后几个字符才能比较出来,肯定就不那么快了。

hash值的计算虽然执行了一系列乘法,不过还是相当迅速。

D语言版本执行了hash值和字符串比较,是比较完善的,效率很不错。C++相应版本看来要提高set的效率才能达到。


jzhang的第一个python版本在我的机器上执行如下:
lijie t # python test2.py
3122.9569912 ms
lijie t # python test2.py
3209.42997932 ms
lijie t # python test2.py
3141.47305489 ms
lijie t # python test2.py
3129.57286835 ms
lijie t # python test2.py
3196.03514671 ms

我做了点修改,执行速度提高了一些:
<!---->#remove duplicated email address from file
import datetime
from time import time
if __name__ == "__main__":
 start 
= time()
 hashtable 
= {}
 f 
= file("email.txt","r")
 f2 
= file("email_new.txt","w")
 
for line in f.xreadlines():
  
if not hashtable.has_key(line):
   hashtable[line] 
= 1
   f2.write(line)
 f.close()
 f2.close()
 print (time() 
- start) * 1000"ms"
在我的机器上执行结果如下:
lijie t # python test1.py
2239.22801018 ms
lijie t # python test1.py
2301.00703239 ms
lijie t # python test1.py
2282.06086159 ms
lijie t # python test1.py
2296.57006264 ms
lijie t # python test1.py
2281.25810623 ms

不过还是没有m网友的效率高。


在F版本的基础上,借鉴m网友的做法,实现一个G版本:

G、排序并去除重复元素,比较hash和字符串版本:
<!---->#include <iostream>
#include 
<string>
#include 
<fstream>
#include 
<iterator>
#include 
<sys/time.h>
#include 
<vector>
using namespace std;


size_t my_hash (
const char* str)
{
        size_t ret 
= 0;
        
while (*str)
                ret 
= 11 * ret + *str++;
        
return ret;
}

class Email
{
private:
        size_t hash;
        
const char* mail;
        friend 
bool operator < (const Email& lhs, const Email& rhs);
public:
        Email (
const char* mail_)
                : hash(my_hash(mail_)), mail(mail_)
        {
        }

        
bool operator == (const Email& rhs)
        {
                
if (hash == rhs.hash)
                        
return strcmp(mail, rhs.mail) == 0;
                
return false;
        }

        
const char* getEmail()const
        {
                
return mail;
        }
};

bool operator < (const Email& lhs, const Email& rhs)
{
        
if (lhs.hash == rhs.hash)
                
return strcmp(lhs.mail, rhs.mail) < 0;
        
return lhs.hash < rhs.hash;
}

int main(int argc, char** argv)
{
        
if (argc < 3)
        {
                cout 
<< "Wrong arguments" << endl;
                
return 1;
        }

        FILE
* fin = fopen(argv[1], "r");
        
if (!fin)
        {
                cout 
<< "Invalid input file" << endl;
                
return 2;
        }
        FILE
* fout = fopen(argv[2], "w");
        
if (!fout)
        {
                fclose(fin);
                cout 
<< "Invalid output file" << endl;
                
return 3;
        }

        timeval start, end;

        
const int BUF_SIZE = 20 * 1024 * 1024;
        
char* buffer = new char[BUF_SIZE];
        memset(buffer, 
0, BUF_SIZE);

        gettimeofday(
&start, 0);
        vector
<Email> emails;

        size_t read 
= fread (buffer, BUF_SIZE, 1, fin);
        
char* begin = buffer;
        
char* current = buffer;

        
while (*current != '\0')
        {
                
if (*current == '\n')
                {
                        
*current = '\0';
                        emails.push_back(begin);
                        begin 
= current + 1;
                }
                
++ current;
        }
        fclose(fin);
        sort(emails.begin(), emails.end());
        emails.erase (unique( emails.begin(), emails.end() ), emails.end());

        
for (vector<Email>::const_iterator iter = emails.begin();
             iter 
!= emails.end();
             iter 
++)
        {
                fputs((
*iter).getEmail(), fout);
                fwrite(
"\n"11, fout);
        }

        fclose(fout);

        gettimeofday(
&end, 0);

        printf(
"Time used: %d ms\n", ((end.tv_sec - start.tv_sec) * 1000 + (end.tv_usec - start.tv_usec) / 1000));

        delete[] buffer;

        
return 0;
}

在我的机器上执行如下:
lijie t # ./test7 email.txt email-new.txt
Time used: 676 ms
lijie t # ./test7 email.txt email-new.txt
Time used: 675 ms
lijie t # ./test7 email.txt email-new.txt
Time used: 671 ms
lijie t # ./test7 email.txt email-new.txt
Time used: 669 ms
lijie t # ./test7 email.txt email-new.txt
Time used: 673 ms

比F版本快了2倍,也快过了其它所有版本。不过由于数据是vector保存的,在数据大量重复的情况下,性能可能会有较大的降低。

把operator<和operator==的实现改为strcmp比较,执行结果如下:
lijie t # ./test8 email.txt email-new.txt
Time used: 1275 ms
lijie t # ./test8 email.txt email-new.txt
Time used: 1267 ms
lijie t # ./test8 email.txt email-new.txt
Time used: 1297 ms
lijie t # ./test8 email.txt email-new.txt
Time used: 1296 ms
lijie t # ./test8 email.txt email-new.txt
Time used: 1271 ms


修改了下,增加了计时,修正了fread使用错误。

<!---->#include <iostream>
#include 
<string>
#include 
<fstream>
#include 
<iterator>
#include 
<vector>
using namespace std;

#ifdef _WIN32
# include 
<windows.h>
#else // _WIN32
# include 
<sys/time.h>
#endif // _WIN32


size_t my_hash (
const char* str)
{
        size_t ret 
= 0;
        
while (*str)
                ret 
= 11 * ret + *str++;
        
return ret;
}

class Email
{
private:
        size_t hash;
        
const char* mail;
        friend 
bool operator < (const Email& lhs, const Email& rhs);
public:
        Email (
const char* mail_)
                : hash(my_hash(mail_)), mail(mail_)
        {
        }

        
bool operator == (const Email& rhs)
        {
                
if (hash == rhs.hash)
                        
return strcmp(mail, rhs.mail) == 0;
                
return false;
        }

        
const char* getEmail()const
        {
                
return mail;
        }
};

bool operator < (const Email& lhs, const Email& rhs)
{
        
if (lhs.hash == rhs.hash)
                
return strcmp(lhs.mail, rhs.mail) < 0;
        
return lhs.hash < rhs.hash;
}

#ifndef _WIN32
class Timer
{
        timeval begin, end;
public:
        
void start () {gettimeofday(&begin, 0);}
        
void stop () {gettimeofday(&end, 0);}
        size_t milliseconds () 
const {
                
return (end.tv_sec - begin.tv_sec) * 1000 + (end.tv_usec - begin.tv_usec) / 1000;
        }
};
#else // _WIN32
class Timer
{
        DWORD begin, end;
public:
        
void start () {begin = GetTickCount();}
        
void stop () {end = GetTickCount();}
        size_t milliseconds () 
const {
                
return end - begin;
        }
};
#endif // _WIN32


int main(int argc, char
分享到:
评论

相关推荐

    常见控制算法的c++/python版本代码实现

    开发者可以根据具体需求调整参数,优化控制性能,并通过C++或Python的代码实现将理论转化为实际应用。理解并掌握这些控制算法及其编程实现对于提升IT专业人士在自动化和控制领域的专业技能至关重要。

    跌倒检测,YOLOV8S,只依赖OPENCV,支持C++/PYTHON

    C++是底层编程语言,可以提供更好的性能和直接的内存控制,而Python则以其简洁的语法和丰富的科学计算库受到欢迎,适合快速原型开发和数据分析。 跌倒检测通常涉及到以下技术点: 1. **预处理**:OpenCV提供了一...

    python与C、C++混编的四种方式(小结)

    例如,在Python项目中引入C或C++代码以提高性能,或者在C/C++应用中嵌入Python脚本以增强灵活性。本文将详细介绍Python与C、C++混编的四种常见方式,并通过具体示例帮助读者理解其应用场景和技术细节。 #### 第一种...

    python32_d.dll和python32_d.lib

    Python32_d.dll和python32_d.lib是C++开发者在嵌入Python解释器进行调试时需要用到的关键组件。这两个文件都是Python的动态链接库(Dynamic Link Library)和库文件,它们为C++程序提供了与Python交互的能力。让我们...

    每天学点C++(C++实例教程:教程+源码)调用python模块.zip

    将C++与Python结合,可以充分利用两者的优点,例如C++的性能优势和Python的易用性。 本教程“每天学点C++(C++实例教程:教程+源码)调用python模块.zip”专注于介绍如何在C++程序中调用Python模块,这通常涉及到...

    python27_d.dll和python27_d.lib动态链接库文件

    3. **lib文件**:`python27_d.lib` 是一个导入库文件,它是C或C++编译器用来链接到`python27_d.dll`的。当编译Python扩展模块或者C/C++程序时,这个文件告诉编译器如何找到DLL中的函数和全局变量。在链接阶段,...

    c++-python 联合游戏

    在游戏开发中,这样的组合可能是为了利用C++的强大性能和Python的易用性与丰富的库资源。C++通常用于编写游戏引擎、底层逻辑和高性能部分,而Python可能用于游戏的脚本编写、AI算法或工具开发。 描述中的信息指出...

    ca源码java-CardRaytracerBenchmark:这是简短的C++/Java/C#/Python基准测试。根据PaulHeckb

    估算性能指标。 得出结论 针对用户的简短说明: 下载并安装Java,Python,CSharp,Digital Mars D,GoLang,JavaScript环境。 运行“运行基准” 阅读报告。 开发者 梅顿 鲁斯兰(基隆) MasterZiv(masterziv) dr-...

    python310-d.zip

    在这个“python310-d.zip”压缩包中,包含了 x64(64位)架构下的调试版本的动态库(python310_d.dll)和静态库(python310_d.lib)。这些库文件对于C++程序员来说非常重要,因为它们允许C++代码与Python环境进行...

    python25_d.lib, python25_d.dll

    总的来说,理解和正确使用`python25_d.lib`和`python25_d.dll`对于在OpenCV中进行Python 2.5的C/C++扩展开发是必不可少的,尤其是在调试阶段,这些文件能提供宝贵的调试信息,帮助开发者找到并修复潜在的问题。...

    python2.7.5源码与python27_d.dll

    Python 2.7.5 源码与 `python27_d.dll` 和 `python27_d.lib` 文件是Python编程语言在Windows平台上的一个重要组成部分。这些文件在开发和调试Python程序时起着至关重要的作用。以下是关于这些知识点的详细说明: **...

    python27.dll python27_d.lib 文件

    3. **编译配置**:如果你在开发C或C++的Python扩展模块,必须确保使用与"python27_d.lib"匹配的编译选项和链接器设置。 4. **版本冲突**:如果你的系统上安装了多个Python版本,可能会出现版本混淆,确保你的程序...

    使用C++调用Python代码的方法详解

    这是一个跨语言交互的重要技术,允许我们利用C++的高性能和Python的丰富库资源。 首先,配置Python环境至关重要。安装Python时,确保将其路径添加到系统环境变量中。这样,无论在哪一级别目录下,C++都能找到Python...

    python37_lib_32bit和python37_lib_64bit

    而"python37.lib"则是Release版本,它优化了性能,适用于部署到生产环境。 在CMake中配置OpenCV的编译过程时,你需要确保指定正确的Python库路径以及对应的架构。如果你正在编译32位版本的OpenCV,需要链接32位的...

    python3.11离线安装依赖包

    Python 3.11 是 Python 语言的最新稳定版本,为开发者提供了更多性能优化和新功能。在 CentOS 7 上进行离线安装 Python 3.11 需要确保系统具备所有必要的依赖包,因为 CentOS 7 默认提供的 Python 版本是 2.7,不...

    使用有限差分的3-D热方程的GPU求解器_C++_Python_下.zip

    标题中的“使用有限差分的3-D热方程的GPU求解器_C++_Python_下.zip”指示了这是一个关于利用GPU加速计算三维热扩散问题的项目,涉及到的主要技术包括有限差分法(Finite Difference Method)和GPU编程,使用的编程...

    python26_d 还有运行时的python26

    在这个压缩包中,我们看到了与 Python 2.6 运行环境相关的几个关键文件,分别是 `python26_d.dll`、`python26.dll`、`python26_d.lib` 和 `python26.lib`。 1. **动态链接库(.dll 文件)**: - `python26.dll`:...

    使用C(C++)扩展 Python(中文文档)

    通过这种方式,您可以利用C/C++的强大性能来实现Python难以完成的任务,比如直接调用C库函数或者进行系统调用。 ##### 创建扩展模块 首先,我们来创建一个名为`spam`的简单扩展模块,该模块将调用C库中的`system()...

    推荐一款python可以使用的游戏引擎.专为U3D打造的游戏服务器引擎

    服务端底层框架使用c++编写,游戏逻辑层使用Python.txt”揭示了KBEngine的设计架构,即用C++实现底层高效性能的部分,而游戏逻辑则用Python编写,这种混合架构既能保证性能,又方便开发。 6. “kbengine引擎-...

    斗山机器人的ROS2_Python_C++_下载.zip

    它支持多种编程语言,包括Python和C++,这两种语言在机器人领域非常常见。斗山机器人(Doosan Robotics)是一家知名的机器人制造商,他们的ROS2开发包提供了与斗山机器人硬件交互的接口。 在这个"斗山机器人的ROS2_...

Global site tag (gtag.js) - Google Analytics