Python Runtime vs C Runtime

Kerry Cao Source

So I wrote a python and a C program to compare runtime, they both write 10^7 bytes to the same file. I expected the C program to have a much shorter time but i was wrong.

BTW, when running the C code, it felt faster than the python code. Also sorry for the lack of comments, it was a spirit of the moment thing and it's pretty simple.

Below is the result and the code for both, any idea why this is happening?


The c program took 4.410720e+05s
The python program took 2.296329s

C Code:

#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

void program(){
    FILE *f;
    f = fopen("temp.txt", "w");

    for(unsigned int i = 1; i <= pow(10,7); i++){
        fprintf(f, "a");


int main(void){
    clock_t begin = clock();


    clock_t end = clock();

    double time_spent = (double)(end - begin);

    FILE *f = fopen("runtime_log","a");
    fprintf(f, "The c program took ");
    fprintf(f, "%les\n",time_spent);

    return 0;

Python Code:

import time

def main():
    start = time.time()


    end = time.time()

    runtime = end - start

    f = open('runtime_log','a')
    f.write('The python program took %fs\n' %runtime)

def program():
    f = open('temp.txt','w')

    for i in range(10**7):



answered 5 days ago Blaze #1

Instead of this:

fprintf(f, "%les\n",time_spent);

Try this:

fprintf(f, "%les\n",time_spent/CLOCKS_PER_SEC);

The reason why your result is wrong is because you assumed it would be seconds, but they're actually of an undisclosed time unit and you need to divide by CLOCKS_PER_SEC to get the amount of seconds.

comments powered by Disqus