# 代码相似性检测

代码相似性检测是一类计算方法，从两个维度衡量两段源代码的相似程度：程序文本的语法，以及代码的语义或行为。<sup>[1](https://arxiv.org/pdf/2306.16171)</sup> 其输出为克隆对或每一对的相似度分数。在抽象模型中，工具将源文件解析为 \( n \) 个代码片段 \( F = \{f_{1}, ..., f_{n}\} \)，考察潜在配对 \( F \times F \)，过滤掉部分配对，再施加一个判定函数，逐一判定剩余配对是否为克隆。<sup>[2](https://clones.usask.ca/pubfiles/articles/SvajlenkoRoyBenchmarksSurvey.pdf)</sup> 其用途包括面向软件维护的克隆检测、编程教育中的抄袭检查，以及漏洞分析。<sup>[3](https://theory.stanford.edu/~aiken/moss/)</sup><sup> • </sup><sup>[4](https://www.mdpi.com/2079-9292/12/22/4671)</sup>

| 关键事实 | 内容 |
|---|---|
| 衡量维度 | 程序文本的语法与语义/行为（功能）<sup>[1](https://arxiv.org/pdf/2306.16171)</sup> |
| 克隆分类 | 1型（仅空白/注释不同）、2型（标识符与字面量不同）、3型（语句级不同）、4型（功能相同、文本不同）<sup>[5](https://cs.uwaterloo.ca/~m2nagapp/courses/CS846/1189/papers/sajnani_icse16.pdf)</sup> |
| 暮光区分层 | 极强3型（90%至不足100%）、强3型（70%至不足90%）、中等3型（50%至不足70%）、弱3型/4型（不足50%）<sup>[6](https://clones.usask.ca/pubfiles/articles/SvajlenkoEvaluatingToolsICSME2015.pdf)</sup> |
| 标准基准 | BigCloneBench：来自25,000个开源Java系统的逾800万个经验证的克隆对，由自动化挖掘识别，克隆对经判定为真阳性或假阳性<sup>[2](https://clones.usask.ca/pubfiles/articles/SvajlenkoRoyBenchmarksSurvey.pdf)</sup><sup> • </sup><sup>[6](https://clones.usask.ca/pubfiles/articles/SvajlenkoEvaluatingToolsICSME2015.pdf)</sup> |
| 可扩展性数据 | SourcererCC在标准工作站上索引2.5亿行代码（250 MLOC）<sup>[5](https://cs.uwaterloo.ca/~m2nagapp/courses/CS846/1189/papers/sajnani_icse16.pdf)</sup> |
| JPlag相似度 | \( \mathrm{sim}(A, B) = 2 \cdot \mathrm{coverage}(\mathrm{tiles}) / (|A| + |B|) \)<sup>[7](https://www.jucs.org/jucs_8_11/finding_plagiarisms_among_a/Prechelt_L.pdf)</sup> |
| 实用工具覆盖范围 | CCFinder、SourcererCC与NiCad对1型和2型有效，对3型部分有效<sup>[8](https://www.mdpi.com/2504-2289/9/2/41)</sup> |

## 工作原理

该领域的共同术语是四型克隆分类法。1型克隆除空白、版式和注释外完全相同；2型克隆在此基础上还存在标识符名称与字面量取值的差异；3型克隆在语句层面存在差异，语句被修改、增加或删除；4型克隆是语法上不相似、但实现相同功能的片段。<sup>[5](https://cs.uwaterloo.ca/~m2nagapp/courses/CS846/1189/papers/sajnani_icse16.pdf)</sup><sup> • </sup><sup>[6](https://clones.usask.ca/pubfiles/articles/SvajlenkoEvaluatingToolsICSME2015.pdf)</sup> 另有一类参数化克隆，是2型克隆的子集，其定义为一个片段的标识符到另一片段标识符的双射映射，因此一致的标识符替换即可复现该副本。<sup>[9](https://drops.dagstuhl.de/storage/16dagstuhl-seminar-proceedings/dsp-vol06301/DagSemProc.06301.13/DagSemProc.06301.13.pdf)</sup>

由于3型相似度是连续变化的，基准测试按语法相似度对3型与4型之间的区域（常被称为“暮光区”）做了细分：极强3型（90%至不足100%）、强3型（70%至不足90%）、中等3型（50%至不足70%）、弱3型/4型（不足50%）。<sup>[10](https://journals.plos.org/plosone/article?id=10.1371%2Fjournal.pone.0296858)</sup> 由于语义分析的复杂性，检测3型和4型克隆仍然颇具挑战。<sup>[8](https://www.mdpi.com/2504-2289/9/2/41)</sup>

## 实现方法

已发表的描述都归结为一条共同的流水线：预处理与归一化，选择一种代码表示（词元序列、抽象语法树或程序依赖图），以及对照阈值进行相似度比较。<sup>[10](https://journals.plos.org/plosone/article?id=10.1371%2Fjournal.pone.0296858)</sup>

**基于词元的工具**在实践中占主导地位。CCFinder对输入的源文本进行变换，然后逐词元比较，可提取C、C++、Java、COBOL等语言中的克隆。<sup>[11](https://dl.acm.org/doi/10.1109/TSE.2002.1019480)</sup> JPlag将每个程序转换为一个规范词元串，并用贪心字符串拼接（Greedy String Tiling）以一个词元串的子串覆盖另一个词元串；其相似度为 \( \mathrm{sim}(A, B) = 2 \cdot \mathrm{coverage}(\mathrm{tiles}) / (|A| + |B|) \)，其中覆盖长度为匹配图块的长度之和，Karp-Rabin式哈希使平均复杂度接近 \( \Theta(|A| + |B|) \)，但最坏情况仍为 \( \Theta((|A| + |B|)^{3}) \)。<sup>[7](https://www.jucs.org/jucs_8_11/finding_plagiarisms_among_a/Prechelt_L.pdf)</sup> NiCad分四步工作：以TXL变换系统在函数、块或整文件粒度上解析；归一化；在用户指定的差异阈值下用优化的最长公共子序列算法比较；以及聚类。<sup>[12](https://research.cs.queensu.ca/home/cordy/Papers/MRC_NiCadModern.pdf)</sup> SourcererCC将代码块作为词元袋比较，采用基于词元顺序的过滤启发式，并使用优化的倒排索引，在标准工作站上达到2.5亿行代码的规模。<sup>[5](https://cs.uwaterloo.ca/~m2nagapp/courses/CS846/1189/papers/sajnani_icse16.pdf)</sup>

## 起源

综述将源代码相似性研究追溯至20世纪70年代，其中包括建立在Halstead对操作数与运算符的软件科学计数之上的工作。<sup>[13](https://www.dcs.warwick.ac.uk/~msj/publications/fulltext/novak_joy_kermek_toce_2019.pdf)</sup> MOSS（Measure Of Software Similarity，软件相似性度量）于1994年开发，主要用于编程课堂中的[抄袭检测](https://www.edgepedia.org/zh/plagiarism-detection)；其指纹匹配基于筛选法（winnowing），这是Saul Schleimer、Daniel S. Wilkerson与Alex Aiken于2003年提出的一种局部文档指纹算法。<sup>[3](https://theory.stanford.edu/~aiken/moss/)</sup> JPlag始于卡尔斯鲁厄大学的一个学生研究项目，数月内便成为在线系统。<sup>[14](https://ics-archive.science.uu.nl/research/techreps/repo/CS-2010/2010-015.pdf)</sup>

在克隆检测方面，Johnson 1993年的指纹工作识别了源代码中的冗余，Dup定义了参数化克隆，Baxter及其同事1998年的ICSM论文引入了基于抽象语法树的克隆检测以及基于程序依赖图的语义技术。<sup>[15](https://pages.cs.wisc.edu/~smithr/pubs/iwsc_2009_paper.pdf)</sup> CCFinder发表于《IEEE软件工程汇刊》28(7)。<sup>[11](https://dl.acm.org/doi/10.1109/TSE.2002.1019480)</sup> GPLAG通过程序依赖图分析检测软件抄袭，由Chao Liu、Chen Chen、Jiawei Han与Philip S. Yu于2006年提出。SourcererCC这一面向大规模代码的基于词元的检测器，由Hitesh Sajnani及其同事于2015年在arXiv（康奈尔大学）上报告。<sup>[16](https://doi.org/10.48550/arxiv.1512.06448)</sup>

## 变体

工具综述将系统分为基于文本（LCS）的工具，如NiCad与CoP，以及基于词元的工具，包括Sherlock、YAP3、JPlag、CCFinder、MOSS与SourcererCC，后者在数百万行源代码的规模上依然高效。<sup>[17](https://link.springer.com/content/pdf/10.1007/s10664-017-9564-7.pdf)</sup>

**基于树与图的方法**以速度换取语义覆盖范围。DECKARD用[欧几里得空间](https://www.edgepedia.org/zh/euclidean-space)中的数值向量刻画抽象语法树的子树，并利用局部敏感哈希按[欧几里得距离](https://www.edgepedia.org/zh/euclidean-distance)对其聚类。<sup>[18](https://psycnet.apa.org/doi/10.1109/ICSE.2007.30)</sup> 其保证是定量性的：若两棵子树间的编辑距离为 \( k \)，则其 \( q \) 级向量间的欧几里得距离至多为 \( (4q - 3) \cdot k \)，从而将树克隆检测转化为最近邻搜索。<sup>[19](https://www.cs.ucdavis.edu/~su/publications/icse08-clone.pdf)</sup> 在此机制之上，有研究者提出了一种可扩展算法，用于检测定义为具有同构程序依赖图的片段的语义克隆，通过将程序依赖图子图映射到其语法像，把图相似性归约为树相似性。<sup>[19](https://www.cs.ucdavis.edu/~su/publications/icse08-clone.pdf)</sup> CCGraph通过近似图匹配检测克隆，采用改造后的Weisfeiler-Lehman图核，以核值与两个程序依赖图总节点数之比衡量相似度，避免了早期程序依赖图工具所用的NP难精确[子图同构](https://www.edgepedia.org/zh/subgraph-isomorphism)。<sup>[20](https://yinxingxue.github.io/papers/ase2020_CCGraph%20A%20PDG%20based%20Code%20Clone%20Detector%20With%20Approximate%20Graph%20Matching.pdf)</sup> CCAligner针对大间隙（重度编辑的3型）克隆，在 \( e \) 编辑距离下匹配代码窗口，采用e失配索引与非对称相似系数，同时在一般的1型至3型检测上保持竞争力。<sup>[21](https://psycnet.apa.org/doi/10.1145/3180155.3180179)</sup>

**基于学习的方法**将代码数值化嵌入。SSCD使用微调后的CodeBERT与GraphCodeBERT嵌入，配合在HNSW图索引上的近似k近邻搜索，取代成对比较，从而在数亿行规模的语料中检测3型与4型克隆。<sup>[22](https://arxiv.org/html/2504.17972v1)</sup> 一种基于图的孪生网络功能相似性方法由Nikita Mehrotra及其同事于2021年发表在《IEEE软件工程汇刊》上。<sup>[23](https://doi.org/10.1109/tse.2021.3105556)</sup> Rator是一种基于节点自由度的树编码检测器，在[Google Code Jam](https://www.edgepedia.org/zh/google-code-jam)上以Top-2排名列表达到100%的细粒度准确率。<sup>[24](https://link.springer.com/article/10.1186/s42400-025-00456-4)</sup>

## 应用

**抄袭检测**将一组学生提交的作业相互比较。MOSS作为互联网服务运行，覆盖多种语言；它会自动消除与预期共享代码（如库或教师提供的文件）的匹配，并且它明确不是全自动的抄袭判定器，因为高亮段落是否构成抄袭必须由人来裁定。<sup>[3](https://theory.stanford.edu/~aiken/moss/)</sup> JPlag在其基准程序集中可靠地检出了77处抄袭中的90%以上，对100份各数百行的提交，运行时间为数秒。<sup>[7](https://www.jucs.org/jucs_8_11/finding_plagiarisms_among_a/Prechelt_L.pdf)</sup>

**克隆检测**服务于维护：在代码库内部及跨代码库查找冗余片段，如NiCad对15个以上开源C与Java系统的研究，其中包括整个Linux内核与Apache httpd。<sup>[25](https://research.cs.queensu.ca/home/cordy/Papers/RC_WCRE08_OSclones.pdf)</sup>

**漏洞搜索**越来越多地使用二进制代码相似性，在无法获取源码的情况下，以一对多或多对多的方式将二进制函数与已知易受攻击函数的数据库比较；一篇综述系统梳理了70种二进制代码相似性方法。<sup>[4](https://www.mdpi.com/2079-9292/12/22/4671)</sup><sup> • </sup><sup>[26](https://dl.acm.org/doi/10.1145/3446371)</sup>

## 局限与替代方案

基于文本的方法能定位完全相同的副本，但容易漏掉经过语法与语义修改的代码。<sup>[17](https://link.springer.com/content/pdf/10.1007/s10664-017-9564-7.pdf)</sup> 可扩展的基于文本与词元的方法无法检测语义克隆，因为它们忽略语义信息；而使用控制流图与程序依赖图的基于图的语义方法虽能捕捉语义，却需要编译才能生成图，且扩展性差。<sup>[24](https://link.springer.com/article/10.1186/s42400-025-00456-4)</sup> 评估受数据制约：机器学习克隆研究依赖BigCloneBench、GoogleCodeJam与OJClone，它们仅覆盖Java与C；2022年的综述发现没有针对Python或C++的公开数据集，也没有跨语言检测的数据集，尽管XCD等较新的数据集此后已开始处理跨语言检测。<sup>[27](https://www.sciencedirect.com/science/article/abs/pii/S1574013722000624)</sup> 对于源码不可得的漏洞搜索，二进制代码相似性是源代码级检测的相关替代方案。<sup>[4](https://www.mdpi.com/2079-9292/12/22/4671)</sup> 近期工作使用预训练模型嵌入，<sup>[22](https://arxiv.org/html/2504.17972v1)</sup> 大语言模型也受到了考察；一项2025年的研究在人类编写与AI生成的代码上，对照四型分类法考察了LLM的克隆检测与相似性评估<sup>[8](https://www.mdpi.com/2504-2289/9/2/41)</sup>，并发现LLM在跨语言[代码克隆检测](https://www.edgepedia.org/zh/code-clone-detection)上表现不佳。<sup>[28](https://jacquesklein2302.github.io/papers/2025-FSE-LLM4Clones.pdf)</sup> 各工具在BigCloneBench上的精确率与召回率分数、由样板代码导致的假阳性率的量化、以及源代码级漏洞复用分析，均未被本文所覆盖的已发表比较所解决。

## References

1. [A systematic literature review on source code similarity measurement (arXiv, 2023)](https://arxiv.org/pdf/2306.16171)
2. [Benchmarks for Software Clone Detection (Svajlenko & Roy survey article)](https://clones.usask.ca/pubfiles/articles/SvajlenkoRoyBenchmarksSurvey.pdf)
3. [Moss: A System for Detecting Software Similarity (Stanford, Alex Aiken)](https://theory.stanford.edu/~aiken/moss/)
4. [A Review of Deep Learning-Based Binary Code Similarity Analysis (Electronics, MDPI)](https://www.mdpi.com/2079-9292/12/22/4671)
5. [SourcererCC: Scaling Code Clone Detection to Big Code (ICSE 2016)](https://cs.uwaterloo.ca/~m2nagapp/courses/CS846/1189/papers/sajnani_icse16.pdf)
6. [Evaluating Clone Detection Tools with BigCloneBench (ICSME 2015)](https://clones.usask.ca/pubfiles/articles/SvajlenkoEvaluatingToolsICSME2015.pdf)
7. [Finding Plagiarisms among a Set of Programs with JPlag (Prechelt et al., JUCS 8(11), 2002)](https://www.jucs.org/jucs_8_11/finding_plagiarisms_among_a/Prechelt_L.pdf)
8. [Exploring the Boundaries Between LLM Code Clone Detection and Code Similarity Assessment on Human and AI-Generated Code (MDPI, 2025)](https://www.mdpi.com/2504-2289/9/2/41)
9. [Survey of Research on Software Clones (Koschke, Dagstuhl Seminar Proceedings)](https://drops.dagstuhl.de/storage/16dagstuhl-seminar-proceedings/dsp-vol06301/DagSemProc.06301.13/DagSemProc.06301.13.pdf)
10. [A systematic literature review on the applications of recurrent neural networks in code clone research (PLOS ONE)](https://journals.plos.org/plosone/article?id=10.1371%2Fjournal.pone.0296858)
11. [CCFinder: a multilinguistic token-based code clone detection system for large scale source code](https://dl.acm.org/doi/10.1109/TSE.2002.1019480)
12. [NiCad: A Modern Clone Detector](https://research.cs.queensu.ca/home/cordy/Papers/MRC_NiCadModern.pdf)
13. [Source-code Similarity Detection and Detection Tools Used in Academia: A Systematic Review (TOCE 2019)](https://www.dcs.warwick.ac.uk/~msj/publications/fulltext/novak_joy_kermek_toce_2019.pdf)
14. [A comparison of plagiarism detection tools (technical report, Utrecht)](https://ics-archive.science.uu.nl/research/techreps/repo/CS-2010/2010-015.pdf)
15. [Detecting and Measuring Similarity in Code Clones (IWSC 2009)](https://pages.cs.wisc.edu/~smithr/pubs/iwsc_2009_paper.pdf)
16. [Sajnani, Hitesh and colleagues (2015). SourcererCC: Scaling Code Clone Detection to Big Code. arXiv (Cornell University).](https://doi.org/10.48550/arxiv.1512.06448)
17. [A comparison of code similarity analysers (Empirical Software Engineering)](https://link.springer.com/content/pdf/10.1007/s10664-017-9564-7.pdf)
18. [DECKARD: A Scalable and Accurate Tree-Based Detection of Code Clones (ICSE 2007)](https://psycnet.apa.org/doi/10.1109/ICSE.2007.30)
19. [Scalable Detection of Semantic Clones (ICSE 2008)](https://www.cs.ucdavis.edu/~su/publications/icse08-clone.pdf)
20. [CCGraph: a PDG-based code clone detector with approximate graph matching (ASE 2020)](https://yinxingxue.github.io/papers/ase2020_CCGraph%20A%20PDG%20based%20Code%20Clone%20Detector%20With%20Approximate%20Graph%20Matching.pdf)
21. [CCAligner (ICSE 2018)](https://psycnet.apa.org/doi/10.1145/3180155.3180179)
22. [Industrial-Scale Neural Network Clone Detection with Disk-Based Similarity Search (arXiv, 2025)](https://arxiv.org/html/2504.17972v1)
23. [Nikita Mehrotra and colleagues (2021). Modeling Functional Similarity in Source Code With Graph-Based Siamese Networks. IEEE Transactions on Software Engineering.](https://doi.org/10.1109/tse.2021.3105556)
24. [Rator: detecting fine-grained semantic code clones using tree encoding based on node degrees of freedom (Cybersecurity, 2025)](https://link.springer.com/article/10.1186/s42400-025-00456-4)
25. [An Empirical Study of Clones in Open Source Software (WCRE 2008)](https://research.cs.queensu.ca/home/cordy/Papers/RC_WCRE08_OSclones.pdf)
26. [A Survey of Binary Code Similar (ACM Computing Surveys)](https://dl.acm.org/doi/10.1145/3446371)
27. [A systematic literature review on the use of machine learning in code clone research (ScienceDirect)](https://www.sciencedirect.com/science/article/abs/pii/S1574013722000624)
28. [The Struggles of LLMs in Cross-Lingual Code Clone Detection (FSE 2025)](https://jacquesklein2302.github.io/papers/2025-FSE-LLM4Clones.pdf)

---
*Initially written Sep 29, 2026 · Reviewed: Sep 30, 2026 · Edited: Sep 30, 2026 · Last review: Sep 30, 2026*

Topic: 技术与人造世界 › 计算技术与数字系统 › 软件与编程 › Software engineering and development process › Software testing and quality

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/code-similarity-detection

English original: https://www.edgepedia.org/code-similarity-detection
