Code comment line counter
Measure how much of a source file explains rather than runs: a six-line snippet with three comment lines and three code lines gives a ratio of 1, with comments at 50 percent. Quoted comment markers are not counted. Free in your browser.
- Free
- Runs in your browser
- No sign-up
- Your data stays on your device
Run — free
Worked example
- Language
- Javascript
- Total lines
- 6
- Blank lines
- 1
- Comment lines
- 3
- Code lines
- 3
The code comment line counter measures how much of a source file is devoted to explanation rather than executable code. Paste source text, choose its language or use automatic detection, and receive counts for comment, code, blank, and mixed lines together with a comment-to-code ratio. The result is a compact documentation-density signal for code review, maintenance planning, quality dashboards, and repository audits. It uses deterministic lexical scanning, keeps quoted comment markers from inflating the count, and makes its chosen language visible in every response.
Read the metric without turning it into a target
Comment density is useful when it starts a conversation, not when it becomes a universal score. This counter divides comment lines by code lines and also presents comments as a percentage of all comment-plus-code observations. A line containing both code and a trailing comment belongs to both categories, while the separate mixed-line count keeps that overlap visible.
Blank lines belong to neither. Those definitions make repeated measurements comparable, but they do not claim that more comments always mean better software. A small parsing function may be clearest with names and tests alone, while a protocol implementation may need extensive notes about invariants and external constraints.
Compare files with similar roles, languages, and maturity. Look for surprising changes: a complicated subsystem whose explanation disappeared, generated code with misleading headers, or a sharp density increase caused by disabled code pasted into comments. Use the result alongside complexity, test coverage, churn, and reviewer judgment.
The metric locates places worth reading; it cannot determine whether a comment is accurate, necessary, or helpful.
Choose a language and understand the counting rules
Select the source language whenever you know it, because comment markers differ. C-family languages use double-slash line comments and slash-star blocks, Python and shell scripts use hash comments, SQL uses double hyphens plus slash-star blocks, and HTML uses markup comment delimiters. Automatic mode inspects common source patterns and returns the inferred language in the result, making the decision explicit instead of hiding it.
The scanner tracks block comments across physical lines and ignores apparent comment markers inside single-quoted, double-quoted, and backtick strings. It classifies each physical line by whether it contains code, comment text, both, or neither. A multi-line block therefore contributes one comment line for every physical line it occupies.
A trailing comment on an executable statement increments both code and comment counts and also increments mixed lines. This lexical approach is deterministic and fast, but it is not a full compiler. Exotic raw-string forms, embedded languages, preprocessor tricks, and language-specific documentation literals can require an explicit language choice or a specialized parser when exact semantic classification is essential.
Apply the result in reviews and maintainability checks
For an individual review, run the counter on the file before and after a change and inspect large shifts rather than enforcing a fixed threshold. A falling ratio in a newly complicated algorithm may signal that assumptions or edge cases need explanation. A rising ratio can be healthy documentation, but it can also reveal commented-out code that should be removed and preserved in version control instead.
At repository scale, store the counts with the commit identifier, language, file path, and generated-file status. Aggregate within comparable groups rather than averaging unrelated files, because configuration, tests, generated clients, and application logic have very different documentation needs. Treat the number as evidence for prioritization: combine it with churn to find frequently edited, poorly explained files; combine it with complexity to focus reviewer attention; and always read the actual comments before drawing conclusions about maintainability.
What you can do with it
Review documentation changes
Compare comment density before and after a patch, then inspect unexpected changes in complex files.
Build a quality dashboard
Record stable line counts and ratios alongside complexity, churn, and test-coverage indicators.
Prioritize maintenance
Find frequently changed modules with unusually little explanatory context for focused review.
FAQ
What is the comment-to-code ratio?
It is the number of comment lines divided by the number of code lines, rounded to six decimal places.
How are lines with code and comments counted?
They count once as code, once as comments, and once in the separate mixed-lines field.
Do blank lines affect the ratio?
No. Blank lines are reported independently and are excluded from both ratio terms.
What happens when a file contains comments but no code?
The ratio field is omitted because division by zero has no finite result; the individual counts remain available.
Is automatic language detection exact?
No. It uses conservative source-pattern rules and reports its choice. Select the language explicitly when accuracy matters.
Does the tool judge comment quality?
No. It measures physical line density, not whether comments are correct, current, or useful.
Related tools
For developers — API access
Everything on this page is available programmatically. This section is for teams who want to wire it into their own systems; everyone else can just use the tool above.
API endpoint
Prefer to automate it? One authenticated POST creates the task; the result comes back by webhook or a signed link. The same capability also runs here on the web, by email and from Telegram — and soon from our app too.
Call it from your stack
curl -X POST https://api.kit.forhosting.com/dev/count-comments \
-H "Authorization: Bearer $KIT_KEY" \
-H "Content-Type: application/json" \
-d '{"text":"// Convert a value\nfunction double(value) {\n return value * 2; // arithmetic\n}"}'const res = await fetch("https://api.kit.forhosting.com/dev/count-comments", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.KIT_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
"text": "// Convert a value\nfunction double(value) {\n return value * 2; // arithmetic\n}"
})
});
const { task_id } = await res.json();import os, requests
res = requests.post(
"https://api.kit.forhosting.com/dev/count-comments",
headers={"Authorization": f"Bearer {os.environ['KIT_KEY']}"},
json={
"text": "// Convert a value\nfunction double(value) {\n return value * 2; // arithmetic\n}"
},
)
task_id = res.json()["task_id"]<?php
$res = file_get_contents("https://api.kit.forhosting.com/dev/count-comments", false, stream_context_create([
"http" => [
"method" => "POST",
"header" => "Authorization: Bearer " . getenv("KIT_KEY") . "\r\nContent-Type: application/json",
"content" => '{"text":"// Convert a value\\nfunction double(value) {\\n return value * 2; // arithmetic\\n}"}',
],
]));
$task = json_decode($res, true);body := bytes.NewBufferString(`{"text":"// Convert a value\nfunction double(value) {\n return value * 2; // arithmetic\n}"}`)
req, _ := http.NewRequest("POST", "https://api.kit.forhosting.com/dev/count-comments", body)
req.Header.Set("Authorization", "Bearer "+os.Getenv("KIT_KEY"))
req.Header.Set("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)Example request
{
"text": "// Convert a value\nfunction double(value) {\n return value * 2; // arithmetic\n}"
}Example response
{
"task_id": "tsk_a1b2c3d4e5f6a1b2c3d4e5f6",
"type": "dev.count_comments",
"status": "queued",
"_links": {
"result": "/tasks/tsk_…/result"
}
}The API is asynchronous: the call returns a task_id immediately and the result arrives by webhook. Polling is capped at 1 req/s per task.
Pricing
Published price — no tokens, no invented credits. A failed task is never charged.
Limits
max_mb | 5 |
Errors
| HTTP | Code | Meaning |
|---|---|---|
401 | unauthorized | Missing or invalid API key. |
402 | insufficient_balance | Your balance doesn't cover the task price. |
404 | unknown_type | That task type doesn't exist. |
429 | rate_limited | Too many requests. Use the webhook instead of polling. |
Technical notes
Apply the result in reviews and maintainability checks
API automation costs $0.002 per request.