首页 \ 问答 \ 为什么功能较慢?(Why is function-less slower?)

为什么功能较慢?(Why is function-less slower?)

我已经构建了一个代码来计算数字的最大素数因子:

import time
start_time = time.time()

num = 600851475143
while num % 2 == 0:
    num /= 2
if num == 1:
    i = 2
else:
    i = 3
    while num > 1:
        if num % i == 0:
            num /= i
        else:
            i += 2
print "%s \n --- %s seconds ---" % (i, time.time() - start_time)

它运行在0.000769853591919秒。 在线搜索我发现了一个类似但更快的解决方案 。 我将这个想法应用到我的代码中,这就是结果:

import time
start_time = time.time()

def lpf(num):
    while num % 2 == 0:
        num /= 2
    if num == 1:
        return 2
    else:
        i = 3
        while num > 1:
            if num % i == 0:
                num /= i
            else:
                i += 2
        return i        

l = lpf(600851475143)

print "%s \n --- %s seconds ---" % (l, time.time() - start_time)

它运行在0.000453948974609秒。 它几乎是前一个的两倍。 我不明白逻辑:代码是相同的,但最长的代码运行得更快。 为什么?


I've built a code to compute the largest prime factor of a number:

import time
start_time = time.time()

num = 600851475143
while num % 2 == 0:
    num /= 2
if num == 1:
    i = 2
else:
    i = 3
    while num > 1:
        if num % i == 0:
            num /= i
        else:
            i += 2
print "%s \n --- %s seconds ---" % (i, time.time() - start_time)

It runs in 0.000769853591919 seconds. Searching online I've found a similar but faster solution. I applied the idea to my code and this is the result:

import time
start_time = time.time()

def lpf(num):
    while num % 2 == 0:
        num /= 2
    if num == 1:
        return 2
    else:
        i = 3
        while num > 1:
            if num % i == 0:
                num /= i
            else:
                i += 2
        return i        

l = lpf(600851475143)

print "%s \n --- %s seconds ---" % (l, time.time() - start_time)

It runs in 0.000453948974609 seconds. It's almost twice as fast as the previous one. I do not understand the logic: the code is identical, but yet the longest code runs faster. Why is it?


原文:https://stackoverflow.com/questions/33508812
更新时间:2021-12-01 22:12

最满意答案

嗯不应该是这样的:

long long res = ((long long)integer<<(sizeof(void*))) | ((long long)ptr);

Thit仍将仅适用于32位指针,不适用于64位。 没有适合这种算术的内置类型。


Hmm shouldn't it be something like:

long long res = ((long long)integer<<(sizeof(void*))) | ((long long)ptr);

Thit will still only work for 32 bit pointers and will not work for 64 bit. There is no built-in type that will fit such arithmetics.

相关问答

更多
  • 嗯不应该是这样的: long long res = ((long long)integer<<(sizeof(void*))) | ((long long)ptr); Thit仍将仅适用于32位指针,不适用于64位。 没有适合这种算术的内置类型。 Hmm shouldn't it be something like: long long res = ((long long)integer<<(sizeof(void*))) | ((long long)ptr); Thit will still only ...
  • 正如评论中提到的那样,你实际上并没有在一个单独的线程中调用函数ackermann 。 你正在做的是直接从main调用函数,将结果存储在int ,并将指向该int的指针作为第三个参数传递给pthread_create ,它应该是指向要运行的函数的指针。 现在, ackermann没有相应的签名传递给pthread_create 。 启动新线程的函数应该像这样声明: void *my_thread_function(void *parameter); 鉴于ackermann是递归调用的,将包装器函数传递给pt ...
  • 当你不需要从函数返回任何东西给函数的调用者时,就会使用void 。 例如。 void no_return_fn() { cout<< "This function will not return anything" << endl; return; // returns nothing or void } 当你必须从函数返回一个整数值给函数的调用者时使用int 例如。 int return_sum_of_integers_fn(int a, int b) { cout<< "Th ...
  • 你的代码是否都在一个功能中? 如果没有, int int_data堆栈中弹出(不是你的队列,实际堆栈),这可能是你打印垃圾的原因; 您正在存储本地变量的地址。 我建议将void* data更改为int data 。 (如果需要,可以将地址存储在int中,然后可以将其转换回指针。) int int_data = 100; push(q, int_data); node* n = pop(q); int num = n->data; 再次查看代码后,添加新节点时会遇到同样的问题。 node new在函数末尾 ...
  • 在C ++中,没有区别。 在C中,差异是有问题的。 有些人认为后一版本(没有void )在技术上只是一个常见的实现扩展,并且不能保证按照标准工作,因为标准中的措辞。 但是,该标准清楚地表明,在函数定义中,一组空白参数具有明确的行为:该函数不接受任何参数。 因此,主要的这样的定义符合标准中的以下描述: 它应该用一个返回类型的int来定义,没有参数。 但是,两者之间存在明显的区别:即,无void的版本无法为该功能提供正确的原型: // this is OK. int main() { if (0) main ...
  • 在C中, void*类型的值(例如由realloc返回的值)可以被分配给int*类型的变量或任何其他对象指针类型。 该值被隐式转换。 错误消息的最可能的解释是,您正在将代码编译为C ++而不是C。确保源文件名以.c结尾,而不是.C或.cpp ,并确保您的编译器配置为编译作为C而不是C ++。 (在C中,投射realloc或malloc的结果被认为是不好的样式。在C ++中,投射是必要的,但通常不会在C ++中首先使用realloc或malloc 。) In C, a value of type void* ...
  • 在大多数现代的普通机器中,可能。 但是,我敢打赌,如果情况并非如此,那么存在一些模糊的编译器或配置(例如,使用32位整数算法的16位寻址机器)。 但是, uintptr_t保证同时拥有这两种类型,所以如果您愿意,可以使用该类型。 In most modern-day commonplace machines, probably. However, I'd bet that there is some obscure compiler or configuration (say, a 16-bit addre ...
  • 让我猜 - 所有的值都转为零? 如果a == b则交换功能会中断。 尝试: void swap(int *a, int *b) { if (a != b) { *a += *b; *b = *a - *b; *a -= *b; } } Let me guess -- all the values turn to zeroes? Your swap function is broken if a == b. Try: void swap(int *a, in ...
  • 这将工作: #include #include void* cloneInt(const void* i) { int *myInt = malloc(sizeof(int)); *myInt = *(int*)i; return myInt; } int main(int argc, char** argv) { int i=10; int *j; j = cloneInt(&i); printf("j: ...
  • 您的问题是您保存临时对象的地址。 例如:在此示例中,您保存临时double d的地址。 __data::__data(double d) { __type = _dt_number; __p = &d; } 该对象仅存在于当前作用域(函数)中,之后地址无用,因为它可能被堆栈中的其他内容覆盖。 我提出的解决方案是制作动态分配的副本: __data::__data(double d) { __type = _dt_number; __p = new double(d); } ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)