utf8の文字コードで構成されたバイナリーファイルがある。このファイルの改行の数を数えよ。改行はCRのみとする。このファイルにはCR が必ず含まれており、CRで分割すればマルチスレッドで処理できる。
size_t count_cr_in_file(const std::string& path) {
std::ifstream fs(path, std::ios::binary);
size_t size = fs.tellg();
fs.seekg(0);
const size_t thread_count = std::thread::hardware_concurrency();
const size_t chunk_size = size / thread_count;
std::vector<std::future<size_t>> futures;
for (size_t t = 0; t < thread_count; t++) {
size_t start = t * chunk_size;
size_t end = (t == thread_count - 1 ? size : (t + 1) * chunk_size);
futures.push_back(std::async(std::launch::async, [start, end, &path]() {
std::ifstream fs(path, std::ios::binary);
fs.seekg(start);
size_t count = 0;
for (size_t i = start; i < end; i++) {
char c;
if (c == '\r') count++;
}
return count;
}));
}
size_t total = 0;
for (auto& f : futures) total += f.get();
return total;
}
import mmap
mm = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
return mm.count(b'\r')
c#で書けと指示したところ、
using System;
using System.IO;
using System.IO.MemoryMappedFiles;
{
public static long CountCRInFile(string path)
{
using var mmf = MemoryMappedFile.CreateFromFile(path, FileMode.Open, null);
using var accessor = mmf.CreateViewAccessor(0, 0, MemoryMappedFileAccess.Read);
long fileSize = accessor.Capacity;
int processorCount = Environment.ProcessorCount;
long chunkSize = fileSize / processorCount;
long total = 0;
object lockObj = new object();
Parallel.For(0, processorCount, i =>
{
long start = i * chunkSize;
long end = (i == processorCount - 1) ? fileSize : (i + 1) * chunkSize;
long localCount = 0;
byte b;
for (long pos = start; pos < end; pos++)
{
if (b == 0x0D) // CR
localCount++;
}
lock (lockObj)
{
total += localCount;
}
});
return total;
}
static void Main(string[] args)
{
long count = CountCRInFile(path);
Console.WriteLine($"CR count = {count}");
}
}
というコードが出てきた。
実際はcrlf,lfもあり得るんだが、そこは考慮しなくてもよく、そう考えるとaiはすごいとしか言いようがない。
大体動くけどなぜかときどき間違えるんだよね・・・
これらのコードの元ネタがwebにあるはずなので出せ。 と質問とした所、 いい質問。ただ、**今回私が提示した C# コード(MemoryMappedFile + Parallel.For で CR を数える)**には、明確に一つ...
なお、最近のaiは元ネタをそのままパクるのは良くないと学習したのか。どうしてそういうことができるのか聞いたところ、 率直に答えます。 --- # 🎯 **なぜ「元ネタを探す」依頼...
で?
このAI、「きゅむむ。きゅむきゅむ」の意味も答えられないのに、こういうことはある程度答えられるんだな。 ※「きゅむむ。きゅむきゅむ」はネットでも使用例がなく、あったとして...