Измерение первого ускорения
Сравните GPU и CPU на одной и той же задаче.
«Измерение первого ускорения» — бесплатный урок CUDA Academy на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения CUDA Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс CUDA Academy содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Now Measure the Win
You have a correct kernel, so the fun question is how much faster it is than the CPU. Measuring turns a guess into a real number. ⏱️
Time the CPU Baseline
Start with a fair baseline: time the same add running in a plain CPU loop. You need something to compare the GPU against.
Don't Time with the Clock Wrong
Avoid timing across a cudaMemcpy you forgot to wait for. The launch is asynchronous, so naive timers can report nonsense.
Use CUDA Events
The right tool is a pair of cudaEvent objects. They record GPU timestamps directly on the device for accurate kernel timing.
cudaEvent_t start, stop;
cudaEventCreate(&start);
cudaEventCreate(&stop);Bracket the Kernel
Record start just before the launch and stop just after. The events queue in the stream alongside your kernel.
cudaEventRecord(start);
vecAdd<<<blocks, threads>>>(d_A, d_B, d_C, n);
cudaEventRecord(stop);Wait, Then Read
Call cudaEventSynchronize on stop so the CPU waits for the GPU. Only then is the elapsed time ready to read.
cudaEventSynchronize(stop);
float ms = 0;
cudaEventElapsedTime(&ms, start, stop);Warm Up First
The very first launch pays one-time setup costs. Run a throwaway warm-up launch before timing so those costs do not skew your number.
Average Several Runs
A single sample is noisy, so time the kernel a few times and take the average. Stable numbers make speedup claims trustworthy.
Count the Copies
Be honest about what you measure. Kernel-only time looks amazing, but real speedup must include the PCIe transfers too.
Compute the Speedup
Speedup is simply CPU time divided by GPU time. A small array may even be slower on the GPU once copies are counted.
float speedup = cpu_ms / gpu_ms;Bigger Arrays Win More
The GPU shines when there is enough work to hide transfer cost. Grow n and watch the speedup climb as parallelism dominates. 📈
Quick Check
Which tool gives accurate GPU kernel timing?
Recap
You measured your first speedup with CUDA events: warm up, bracket the kernel, sync, and divide CPU by GPU time. Bigger problems, bigger wins. 🎉
Часто задаваемые вопросы
Урок «Измерение первого ускорения» бесплатный?
Да — полный текст урока «Измерение первого ускорения» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс CUDA Academy, подпишись на CoddyKit PRO. Курс CUDA Academy содержит 4 уроков всего.
Чему я научусь в уроке «Измерение первого ускорения»?
Сравните GPU и CPU на одной и той же задаче. Ты практикуешь CUDA Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать CUDA Academy?
Предыдущий опыт не требуется. CUDA Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «Измерение первого ускорения»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке CUDA Academy?
Да. Каждый урок CUDA Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Ядро сложения векторов
- Настройка части для хоста
- Проверка результата на CPU
- Измерение первого ускорения